首页 > 代码库 > 详解C#中Socket通信(一):实现连接

详解C#中Socket通信(一):实现连接

第一步:实现连接

客户端连接代码:

private void connect2Server()

{

Socket clientSocket;

//服务器地址

IPAddress ip = IPAddress.Parse("192.168.1.136");

//服务器节点 IPEndPoint iep = new IPEndPoint(ip, 9004);

//通信实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

//连接 clientSocket.Connect(iep);

}

客户端通过Socket连接到服务器的9004端口。

 

服务器接受连接代码:

public void StartListening()

{

//获取本机IP地址

Socket serverSocket; IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName()); HostIP = ipHost.AddressList[0];

//开关控制

bool flag=true; try {     IPEndPoint iep = new IPEndPoint(HostIP, 9004);

    serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     serverSocket.Bind(iep);

    //最大100个     serverSocket.Listen(100);                 //如果有客户端连接进来,就加入队列                    while (flag)     {                             //阻塞侦听是否有客户端连接

        clientSocket = serverSocket.Accept();         if (clientSocket != null)         {                                     string str = clientSocket.RemoteEndPoint.ToString();             string[] Ipstr = str.Split(‘:‘);

            string clientIp = Ipstr[0];

            MessageBox("客户端:"+clientIp+"连接到服务器");

        }

    } } catch (Exception e) {               

    MessageBox.show("连接错误:"+e.message); }

}

服务器启动Socket,侦听是否有客户端进入,如果有的话,加入队列。通常情况下,为了使客户端和服务器对其它事件进行响应,把它们放置在独立线程进行。类似下面的代码:

Thread _createServer;

_createServer = new Thread(new ThreadStart(StartListening)); _createServer.IsBackground = true; _createServer.Start();