C# Socket 实现多端口通信

基本思路是:

1》服务端监听(用一个公用的端口接收连接的请求如:6666)
2》客户机请求连接端口为6666 
3》服务器接受请求然后再监听一个新的端口,再把这个端口发送给客户机
4》客户机接到发来的端口,再重新连接服务器此端口
5》服务器保存每一个连接的客户机 (文/YangLei's

服务端代码如下
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Net.Sockets;
  10. using System.Net;
  11. using System.Collections;
  12. using System.Threading;

  13. namespace 多端口服务端
  14. {
  15.     public partial class Form1 : Form
  16.     {
  17.         public Form1()
  18.         {
  19.             InitializeComponent();
  20.             slist = aa =>
  21.             {
  22.                 listBox1.Items.Add(aa);
  23.             };
  24.         }
  25.         private int localPort = 6666;
  26.         private delegate void SetListBoxCallBack(string str);
  27.         private SetListBoxCallBack slist;
  28.         private static int PID = 6667;
  29.         private static ArrayList clientList = new ArrayList();
  30.         private void button1_Click(object sender, EventArgs e)
  31.         {
  32.             AcceptConnection();
  33.         }
  34.         //开始监听的回调函数
  35.         private void AcceptConnection()
  36.         {
  37.             try
  38.             {
  39.                 Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  40.                 IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
  41.                 // 将 Socket 绑定到本地的终结点上
  42.                 mainSocket.Bind(localEP);
  43.                 // 开始侦听,最大的连接数是 50
  44.                 mainSocket.Listen(50);
  45.                 mainSocket.BeginAccept(new AsyncCallback(AcceptCallBack), mainSocket);
  46.             }
  47.             catch (Exception ex)
  48.             {
  49.                 MessageBox.Show(ex.Message);
  50.             }
  51.         }
  52.         //接收连接的回调函数
  53.         private void AcceptCallBack(IAsyncResult iar)
  54.         {
  55.             try
  56.             {
  57.                 Socket mainSocket = (Socket)iar.AsyncState;
  58.                 // 调用EndAccept完成BeginAccept异步调用,返回一个新的Socket处理与客户的通信
  59.                 Socket workerSocket = mainSocket.EndAccept(iar);
  60.                 
  61.                 if (mainSocket.LocalEndPoint.ToString().IndexOf("6666") != -1)
  62.                 {
  63.                     int NewPid = PID++;
  64.                     localPort = NewPid;
  65.                     AcceptConnection();
  66.                     SendData(System.Text.Encoding.Default.GetBytes("PID|" + NewPid), workerSocket);
  67.                 }
  68.                 else
  69.                 {
  70.                     // 存储客户端sokect
  71.                     clientList.Add(workerSocket);
  72.                     listBox1.Invoke(slist, workerSocket.RemoteEndPoint.ToString());
  73.                 }
  74.                 mainSocket.BeginAccept(new AsyncCallback(AcceptCallBack), mainSocket);
  75.             }
  76.             catch (Exception ex)
  77.             {
  78.                 throw;
  79.             }
  80.         }
  81.         public void SendData(byte[] buffer, Socket workerSocket)
  82.         {
  83.             try
  84.             {
  85.                 int left = buffer.Length;
  86.                 int sndLen = 0;
  87.                 workerSocket.BeginSend(buffer, sndLen, left, SocketFlags.None, new AsyncCallback(SendCallBack), workerSocket);
  88.             }
  89.             catch (SocketException ex)
  90.             {
  91.                 MessageBox.Show(ex.Message);
  92.             }
  93.         }
  94.         private void SendCallBack(IAsyncResult iar)
  95.         {
  96.             Socket workerSocket = (Socket)iar.AsyncState;
  97.             workerSocket.EndSend(iar);
  98.         }

  99.         private void button2_Click(object sender, EventArgs e)
  100.         {
  101.             byte[] buffer=System.Text.Encoding.Default.GetBytes("mesg|"+textBox1.Text);
  102.             int snLen=0;
  103.             listBox2.Items.Add(textBox1.Text);
  104.             while(true)
  105.             for (int i = 0; i < clientList.Count; i++)
  106.             {
  107.                 int k = i;
  108.                 Thread aa = new Thread(new ThreadStart(()=>
  109.                 {
  110.                     ((Socket)clientList[k]).BeginSend(buffer, snLen, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ((Socket)clientList[k]));
  111.                 }));
  112.                 aa.IsBackground = true;
  113.                 aa.Start();  
  114.             }
  115.         }
  116.     }
  117. }
复制代码
客户端代码:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Net;
  10. using System.Net.Sockets;

  11. namespace 多端口客户端
  12. {
  13.     public partial class Form1 : Form
  14.     {
  15.         public Form1()
  16.         {
  17.             InitializeComponent();
  18.             label = (text,la) =>
  19.             {
  20.                 la.Text = text;
  21.             };
  22.             slist = aa =>
  23.             {
  24.                 listBox1.Items.Add(aa); 
  25.             };
  26.         }
  27.         private int serverPort = 6666;
  28.         public byte[] dataBuffer = new byte[10000000];
  29.         private Socket client;
  30.         private delegate void setLabel(string text,Label la);
  31.         private setLabel label;
  32.         private delegate void SetListBoxCallBack(string str);
  33.         private SetListBoxCallBack slist;
  34.         private void button1_Click(object sender, EventArgs e)
  35.         {
  36.             ServerConnection();
  37.         }
  38.         //连接服务器
  39.         private void ServerConnection()
  40.         {
  41.             try
  42.             {
  43.                 IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("192.169.1.113"), serverPort);
  44.                 client = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  45.                 client.Connect(ipEndPoint);
  46.                 label1.Invoke(label, client.RemoteEndPoint.ToString(),label1);
  47.                 label2.Invoke(label, client.LocalEndPoint.ToString(), label2);
  48.                 client.BeginReceive(dataBuffer, 0, dataBuffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), client);
  49.             }
  50.             catch (Exception ex)
  51.             {
  52.                 throw;
  53.             }

  54.         }
  55.         //回调接收函数
  56.         private void RecieveCallBack(IAsyncResult iar)
  57.         {
  58.             Socket socketData = (Socket)iar.AsyncState;
  59.             int iRx = socketData.EndReceive(iar);
  60.             string revStr = System.Text.Encoding.Default.GetString(dataBuffer, 0, iRx);
  61.             string[] str = revStr.Split('|');
  62.             if (str[0] == "PID")
  63.             {
  64.                 serverPort =Convert.ToInt32(str[1]);
  65.                 ServerConnection();
  66.             }
  67.             if (str[0] == "mesg")
  68.             {
  69.                 listBox1.Invoke(slist, str[1]);
  70.                 socketData.BeginReceive(dataBuffer, 0, dataBuffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), socketData);
  71.             }
  72.             
  73.         }
  74.     }
  75. }
复制代码
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值