在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
服务端: void Main() { Socket socketA = null; Socket socketB = null; var maxWaitingRequest = 10; var localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); localSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true); localSocket.Bind(new IPEndPoint(IPAddress.Any, 81)); localSocket.Listen(maxWaitingRequest); while (true) { var remoteSocket = localSocket.Accept(); if (socketA == null) //client socketA = remoteSocket; else if (socketB == null) //server { socketB = remoteSocket; ThreadPool.QueueUserWorkItem(new WaitCallback(transfer), new Socket[] { socketA, socketB }); ThreadPool.QueueUserWorkItem(new WaitCallback(transfer), new Socket[] { socketB, socketA }); } } } public static void transfer(object obj) { var socketA = ((Socket[])obj)[0]; var socketB = ((Socket[])obj)[1]; while (true) { try { var data = new byte[10240]; int read = socketA.Receive(data); if(read > 0) socketB.Send(data.Take(read).ToArray()); } catch { socketA.Close(); socketA.Close(); break; } } } 客户端: static Queue<string> msgList = new Queue<string>(); static readonly object msgLocker = new Object(); static int localPort = 20000; static string msg = "I am A"; void Main() { var localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var localEP = new IPEndPoint(IPAddress.Any, localPort); localSocket.Bind(localEP); localSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 81)); ThreadPool.QueueUserWorkItem(recieveHandler, localSocket); Thread.Sleep(10000); localSocket.Send(System.Text.Encoding.Default.GetBytes(msg)); while (true) { lock (msgLocker) { if(msgList.Count >0) Console.WriteLine(msgList.Dequeue()); } Thread.Sleep(1000); } } public static void recieveHandler(object p) { var localSocket = (Socket)p; while (true) { var data = new byte[1024]; var read = localSocket.Receive(data); if (read > 0) { Console.WriteLine("recieved " + read.ToString() + " bytes"); lock (msgLocker) msgList.Enqueue(System.Text.Encoding.Default.GetString(data.Take(read).ToArray())); } } } // Define other methods and classes here 先启动服务端,在10秒内,启动两个客启端,两个客户端就能收到来自对方的 msg |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论