socket 异步接收连接和接收数据
Posted wlzhang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket 异步接收连接和接收数据相关的知识,希望对你有一定的参考价值。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using System.Threading; using System.Net; using Newtonsoft.Json; namespace WindowsSocket { public class Msg { public int Flag { get; set; } public string Message { get; set; } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } //如果一次接收不了,会多次进入OnMessage方法解析 byte[] buffer = new byte[1024]; public void OnMessage(IAsyncResult result) { //result.AsyncState 为调用BeginReceive 传递过来的参数 Socket ts = (Socket)result.AsyncState; //获取接收到信息的长度 //int count = ts.EndReceive(result); //result.AsyncWaitHandle.Close(); this.textBox1.Invoke(new EventHandler(delegate { var msg = Encoding.ASCII.GetString(buffer); MessageBox.Show(msg); //var objects = JsonConvert.DeserializeObject<Msg>(msg); //MessageBox.Show(objects.Flag.ToString()); //MessageBox.Show(objects.Message.ToString()); //textBox1.Text += ts.RemoteEndPoint.ToString() + "客户端信息" + Encoding.ASCII.GetString(buffer) + "\r\n"; })); ts.Send(Encoding.ASCII.GetBytes("How are you? I got a message")); //清空数据,重新开始异步接收 //buffer = new byte[buffer.Length]; ts.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnMessage), ts); } /// 异步连接客户端 /// </summary> /// <param name="tcpServer"></param> private void AsynAccept(Socket tcpServer) { tcpServer.BeginAccept(asyncResult => { //取得终端Socket Socket socketAccept = tcpServer.EndAccept(asyncResult); //获取客户端地址信息 if (socketAccept.RemoteEndPoint is IPEndPoint) { //var ss = tcpClient.Receive(buffer); //异步获取数据 socketAccept.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnMessage), socketAccept); //byte[] msg = new byte[tcpServer.ReceiveBufferSize]; //tcpServer.Receive(msg); //textBox1.Invoke(new EventHandler(delegate //{ // textBox1.Text += "客户端信息" + tcpClient.RemoteEndPoint.ToString() + "\r\n"; //})); } //持续监听终端连接 AsynAccept(tcpServer); }, null); } //开启socket服务端 private void button1_Click(object sender, EventArgs e) { Task task = new Task(() => { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8877)); socket.Listen(1111); AsynAccept(socket); }); task.Start(); } } }
以上是关于socket 异步接收连接和接收数据的主要内容,如果未能解决你的问题,请参考以下文章