Socket基本编程

两台机器的聊天程序!服务端打开,准备接受客户端数据,然后在另外一台机器上运行客户端,输入服务端IP,端口,就可以聊天了.

===Client客户端===

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
//客户端
class SocketClientTester
{
    private void BeginSend()
    {
        string ip = this.txtip.Text;
        string port = this.txtport.Text;
        IPAddress serverIp = IPAddress.Parse(ip);
        int serverPort = Convert.ToInt32(port);
        IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
        byte[] byteMessage;
        //   do
        //   {
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect(iep);
        byteMessage = Encoding.ASCII.GetBytes(textBox1.Text);
        socket.Send(byteMessage);
        socket.Shutdown(SocketShutdown.Both);
        socket.Close();
        //   }
        //   while(byteMessage!=null);
    }
    private void button1_Click(object sender, System.EventArgs e)
    {
        BeginSend();
    }
}

===Server服务器端===

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class SocketTester   //Server(Port:8000)
{
    Thread mythread;
    Socket socket;

    protected override void Dispose(bool disposing)
    {
        try
        {
            socket.Close();//释放资源 
            mythread.Abort();//中止线程 
        }
        catch { }

        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }
        }
        base.Dispose(disposing);
    }
    
    public static IPAddress GetServerIP()
    {
        IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName());
        return ieh.AddressList[0];
    }

    private void BeginListen()
    {
        IPAddress ServerIp = GetServerIP();
        IPEndPoint iep = new IPEndPoint(ServerIp, 8000);
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        byte[] byteMessage = new byte[100];
        this.label1.Text = iep.ToString();

        socket.Bind(iep);
        //   do
        while (true)
        {
            try
            {
                socket.Listen(5);
                Socket newSocket = socket.Accept();
                newSocket.Receive(byteMessage);

                string sTime = DateTime.Now.ToShortTimeString();
                string msg = sTime + ":" + "Message from:" + newSocket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage);
                this.listBox1.Items.Add(msg);
            }
            catch (SocketException ex)
            {
                this.label1.Text += ex.ToString();
            }
        }
        //   while(byteMessage!=null);
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        try
        {
            mythread = new Thread(new ThreadStart(BeginListen));
            mythread.Start();
        }
        catch (System.Exception er)
        {
            MessageBox.Show(er.Message, "完成", MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
    }

    private void btnexit_Click(object sender, System.EventArgs e)
    {
        if (mythread != null)
        {
            if (mythread.IsAlive)
            {
                mythread.Abort();
            }
        }
        Application.Exit();
    }
}
Contributors: FHL