Sockets通信实现代码

学习一个新的东西,首先要知道其原理,对于Sockets的学习,可先看一下文档:http://blog.csdn.net/hulihui/article/details/3230503#st     点击打开链接

刚开始是写代码实现了一个客户端和服务器的通讯,后来完善代码,实现了多个客户端与服务器端的通讯,由于原理是差不多的,这里就直接介绍多个客户端与服务器进行通讯。

第一部分  窗体设计

1.服务器端


2.客户端


第二部分  代码

1.服务器端:
– 申请一个socket (socketWatch)用来监听的
– 绑定到一个IP地址和一个端口上
– 开启侦听,等待接授客户端的连接
– 当有连接时创建一个用于和连接进来的客户端进行通信的socket(socketConnection)
– 即续监听,等侍下一个客户的连接

[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //服务器端  
  2. using System.IO;  
  3. using System.Net;  
  4. using System.Threading;  
  5. using System.Net.Sockets;  
  6.   
  7. namespace SocketsServer  
  8. {  
  9.     public partial class Form1 : Form  
  10.     {  
  11.         public Form1()  
  12.         {  
  13.             InitializeComponent();  
  14.         }  
  15.   
  16.         Socket socketWatch = null;  
  17.         Thread threadWatch = null;  
  18.   
  19.         private void startconn_Click(object sender, EventArgs e)  
  20.         {  
  21.             socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  22.             IPAddress ipaddress = IPAddress.Parse(localip.Text.Trim());  
  23.             IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(porttext.Text.Trim()));  
  24.             socketWatch.Bind(endpoint);  
  25.   
  26.   
  27.             socketWatch.Listen(10);  
  28.   
  29.             threadWatch = new Thread(WatchingConn);  
  30.             threadWatch.IsBackground = true;  
  31.             threadWatch.Start();  
  32.   
  33.             this.Invoke(new Action(() =>  
  34.             {  
  35.                 recmsg.AppendText("开始对客户端进行监听!" + "\r\n");  
  36.             }  
  37.                 ));  
  38.   
  39.         }  
  40.   
  41.           
  42.   
  43.         //保存了服务器端所有负责和客户端通信发套接字  
  44.         Dictionary<string, Socket> dictSocket = new Dictionary<string, Socket>();  
  45.         //保存了服务器端所有负责调用通信套接字.Receive方法的线程  
  46.         Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();  
  47.   
  48.   
  49.         //Socket socConn = null;  
  50.   
  51.         private void WatchingConn(object obj)  
  52.         {  
  53.   
  54.             while (true)  
  55.             {  
  56.                 Socket socConn = socketWatch.Accept();  
  57.   
  58.                 this.Invoke(new Action(() => {  
  59.                     //向下拉项中添加一个客户端的ip端口字符串,作为客户端的唯一标识  
  60.                     iptext.Items.Add(socConn.RemoteEndPoint.ToString());  
  61.                 }));  
  62.                   
  63.                 将与客户端通信的套接字对象sokConn添加到键值对集合中,并以客户端IP端口作为键  
  64.                 dictSocket.Add(socConn.RemoteEndPoint.ToString(), socConn);  
  65.                   
  66.   
  67.                 ParameterizedThreadStart pts = new ParameterizedThreadStart(RecMsg);  
  68.                 Thread trd = new Thread(pts);  
  69.                 trd.IsBackground = true;  
  70.                 trd.Start(socConn);  
  71.   
  72.                 dictThread.Add(socConn.RemoteEndPoint.ToString(), trd);  
  73.                 this.Invoke(new Action(()=>  
  74.                     {  
  75.                         recmsg.AppendText("客户端连接成功!" + "\r\n");  
  76.                     }  
  77.                     ));  
  78.   
  79.             }  
  80.   
  81.         }  
  82.   
  83.         private void RecMsg(object socketClientPara)  
  84.         {  
  85.             Socket socketRec = socketClientPara as Socket;  
  86.   
  87.             while (true)  
  88.             {  
  89.                 byte[] arrRecMsg = new byte[1024 * 1024];  
  90.   
  91.                 //int length = socketClient.Receive(arrRecMsg);//......wrong......  
  92.   
  93.                 int length = -1;  
  94.                 try  
  95.                 {  
  96.                     length = socketRec.Receive(arrRecMsg);  
  97.                 }  
  98.                 catch (SocketException ex)  
  99.                 {  
  100.                     MessageBox.Show("异常:" + ex.Message);  
  101.                     //从通信套接字集合中删除被中断连接的通信套接字对象  
  102.                     dictSocket.Remove(socketRec.RemoteEndPoint.ToString());  
  103.                     //从通信线程结合中删除被终端连接的通信线程对象  
  104.                     dictThread.Remove(socketRec.RemoteEndPoint.ToString());  
  105.                     //从列表中移除被中断的连接 ip:Port  
  106.                     iptext.Items.Remove(socketRec.RemoteEndPoint.ToString());  
  107.                     break;  
  108.                 }  
  109.   
  110.                 catch (Exception ex)  
  111.                 {  
  112.                     MessageBox.Show("异常:" + ex.Message);  
  113.                     break;  
  114.                 }  
  115.   
  116.                 string str = Encoding.UTF8.GetString(arrRecMsg, 0, length);  
  117.                 this.Invoke(new Action(() => {  
  118.                     recmsg.AppendText(iptext.Text + ":\r\n" + GetTime() + "\r\n" + str + "\r\n");  
  119.                 }));  
  120.   
  121.   
  122.                 Thread.Sleep(10);  
  123.             }  
  124.         }  
  125.   
  126.         private DateTime GetTime()  
  127.         {  
  128.             DateTime getTime = new DateTime();  
  129.             getTime = DateTime.Now;  
  130.             return getTime;  
  131.         }  
  132.   
  133.   
  134.         private void SendMsg(string sendMsg)  
  135.         {  
  136.             if (string.IsNullOrEmpty(iptext.Text))  
  137.             {  
  138.                 MessageBox.Show("请选择通信IP!");  
  139.             }  
  140.   
  141.             else  
  142.             {  
  143.                 byte[] strSendMsg = Encoding.UTF8.GetBytes(sendMsg);  
  144.                 string strClientKey = iptext.Text;//通过Key匹配对应ip地址的客户端  
  145.   
  146.                 dictSocket[strClientKey].Send(strSendMsg);  
  147.   
  148.                 this.Invoke(new Action(() =>  
  149.                 {  
  150.                     recmsg.AppendText("服务器:" + "\r\n" + GetTime() + "\r\n" + sendMsg + "\r\n");  
  151.   
  152.                 }));  
  153.                 sendmsg.Text = null;  
  154.   
  155.             }  
  156.         }  
  157.   
  158.         private void sendok_Click(object sender, EventArgs e)  
  159.         {  
  160.             SendMsg(sendmsg.Text.Trim());  
  161.   
  162.         }  
  163.   
  164.   
  165.     }  
  166. }  
2.客户端:
– 申请一个socket
– 连接服务器(指明IP地址和端口号)
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //客户端  
  2. using System.IO;  
  3. using System.Net;  
  4. using System.Net.Sockets;  
  5. using System.Threading;  
  6.   
  7. namespace SocketsClient  
  8. {  
  9.     public partial class Form1 : Form  
  10.     {  
  11.         public Form1()  
  12.         {  
  13.             InitializeComponent();  
  14.         }  
  15.   
  16.         Socket socketWatch = null;  
  17.         Thread threadWatch = null;  
  18.   
  19.         private void startconn_Click(object sender, EventArgs e)  
  20.         {  
  21.             socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  22.             IPAddress address = IPAddress.Parse(iptext.Text.Trim());  
  23.             IPEndPoint endpoint = new IPEndPoint(address, int.Parse(porttext.Text.Trim()));  
  24.   
  25.             socketWatch.Connect(endpoint);  
  26.            // socketWatch.Bind(endpoint);//...报错(服务器是Bind,客户端是Connect)...  
  27.   
  28.             threadWatch = new Thread(RecMsg);  
  29.             threadWatch.IsBackground = true;  
  30.             threadWatch.Start();  
  31.   
  32.         }  
  33.   
  34.   
  35.        
  36.   
  37.         private void RecMsg(object obj)  
  38.         {  
  39.             while (true)  
  40.             {  
  41.                 byte[] arrRecMsg = new byte[1024 * 1024];  
  42.                 int length = socketWatch.Receive(arrRecMsg);  
  43.                 string str = Encoding.UTF8.GetString(arrRecMsg, 0, length);  
  44.                 this.Invoke(new Action(() => {  
  45.                     recmsg.AppendText("服务器:" + "\r\n" + GetTime() + "\r\n" + str + "\r\n");  
  46.                 }));  
  47.   
  48.             }  
  49.         }  
  50.   
  51.         private DateTime GetTime()  
  52.         {  
  53.             DateTime getTime = new DateTime();  
  54.             getTime = DateTime.Now;  
  55.             return getTime;  
  56.         }  
  57.   
  58.   
  59.         private void SendMsg(string sendMsg)  
  60.         {  
  61.             byte[] strSenMsg = Encoding.UTF8.GetBytes(sendMsg);  
  62.             socketWatch.Send(strSenMsg);  
  63.   
  64.             this.Invoke(new Action(() =>  
  65.             {  
  66.                 recmsg.AppendText("客户端:" + "\r\n" + GetTime() + "\r\n" + sendMsg + "\r\n");  
  67.             }));  
  68.             sendmsg.Text = null;  
  69.         }  
  70.         private void sendok_Click(object sender, EventArgs e)  
  71.         {  
  72.             SendMsg(sendmsg.Text.Trim());  
  73.         }  
  74.     }  
  75. }  


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值