参考视频:
C#之Socket编程 | 简单聊天工具 | 全集完
为最终的界面化,增删改成做铺垫
期望:实现两台电脑之间的即时聊天。
具体:一台电脑的客户端做为服务器端,另一台电脑做为客户端。
服务器端开启端口,监听其他电脑对这个端口的请求。一旦发现有电脑接入,就建立连接。

TcpListener listener; IPAddress ip; private void btnStart_Click(object sender, EventArgs e) { ip = IPAddress.Parse(txtBoxIP.Text);//创建IP listener = new TcpListener(ip, Convert.ToInt32(txtBoxPort.Text));//创建TCP监听对象 listener.Start();//开始监听 txtBoxInfo.Text = "服务器启动"+DateTime.Now.ToShortDateString()+"\r\n"+txtBoxInfo.Text; ; } 

TcpClient tcpClient; private void btnConnect_Click(object sender, EventArgs e) { tcpClient = new TcpClient();//实例化客户端对象 try { tcpClient.Connect(txtBoxIP.Text, Convert.ToInt32(txtBoxPort.Text));//客户端和服务器端建立链接 txtBoxInfo.Text = "链接成功-" + DateTime.Now.ToShortDateString() + "\r\n" + txtBoxInfo.Text; } catch (Exception ex) { MessageBox.Show($"链接失败,{ex.Message}"); } } 

Console.WriteLine("链接成功, 我方端口{ 0},服务器端口{ 1}", tcpClient.Client.LocalEndPoint, tcpClient.Client.RemoteEndPoint); 客户端会自动分配一个端口,和服务器端的9500端口进行匹配链接。
客户端的端口是不需要程序分配的,这是因为每次都可能不一样。
服务器端的9500端口是可以和多个客户端连接的。
上一篇:华为荣耀4x安卓5.0