1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C# Socket异步通讯

C# Socket异步通讯

时间:2020-12-26 14:32:21

相关推荐

C# Socket异步通讯

客户端:

Socket sock = null;byte[] buffer = new byte[1024];private void btnStart_Click(object sender, EventArgs e){try{sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);IPAddress ip = IPAddress.Parse(txtServer.Text);IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//获得要连接的远程服务器应用程序的IP地址和端口号//sock.BeginConnect(point, new AsyncCallback(ConnectServer), sock);//铜鼓sock.Connect(point);ShowTxtLog("连接成功");sock.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(CallReveive), sock);btnStart.Enabled = false;}catch{Action ac = () => { btnStart.Enabled = true; };}}private void ConnectServer(IAsyncResult Iay){Socket sock = Iay.AsyncState as Socket;if (sock != null){sock.EndConnect(Iay);}}private void CallReveive(IAsyncResult Iay){try{Socket sock = Iay.AsyncState as Socket;if (sock != null && IsSocketConnected(sock)){int len = sock.EndReceive(Iay);string s = Encoding.Default.GetString(buffer, 0, len);ShowTxtLog(s);}if (sock != null && IsSocketConnected(sock)){sock.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(CallReveive), sock);}}catch (Exception e) { Action ac = () => { btnStart.Enabled = true; }; }}public bool IsSocketConnected(Socket s){if (s == null)return false;return !((s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)) || !s.Connected);}private void ShowTxtLog(string s){Action ac = () => {txtLog.AppendText(s+"\r\n");};Invoke(ac);}private void btnSend_Click(object sender, EventArgs e){if (sock != null && IsSocketConnected(sock)){byte[] data = Encoding.Default.GetBytes(txtMsg.Text);sock.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(CallBackSend), sock);}}private void CallBackSend(IAsyncResult Iay){Socket sock = Iay.AsyncState as Socket;if (sock != null){int len= sock.EndSend(Iay);ShowTxtLog("客户端发送"+len +"个字节");}}

服务端:

//服务端buffer为4字节static byte[] buffer = new byte[1024];private void button1_Click(object sender, EventArgs e){try{Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);socketServer.Bind(new IPEndPoint(IPAddress.Parse(textBox1.Text ), Convert.ToInt32(textBox2.Text)));socketServer.Listen(int.MaxValue);ShowText3("服务端已启动,等待连接...");//接收连接//Socket ts = socketServer.Accept();socketServer.BeginAccept(new AsyncCallback(ClientAccepted), socketServer);//ShowText3("客户端已连接");//开始异步接收//ts.BeginServer(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ts);button1.Enabled = false;}catch (Exception ex){Action ac = () => { button1.Enabled = true; };Console.WriteLine(ex.Message);}}Socket socketsend = null;public void ClientAccepted(IAsyncResult ar){var socket = ar.AsyncState as Socket;//客户端Socket实例,后续保存if (socket != null){socketsend = socket.EndAccept(ar);//客户端IP地址和端口信息//IPEndPoint colientip = (IPEndPoint)client.RemoteEndPoint;//Console.WriteLine(colientip + "客户已连接", ConsoleColor.Yellow);ShowText3("客户已连接");//接受客户端消息socketsend.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMsg), socketsend);//socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);}//准备接受下一个客户端连接请求if (socket != null) socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);}//接受客户端的消息public void ReceiveMsg(IAsyncResult ar){Socket socket = ar.AsyncState as Socket;//客户端IP地址和端口消息if (socket != null ){try{var length = socket.EndReceive(ar);var message = Encoding.UTF8.GetString(buffer, 0, length);//Console.WriteLine(clientipe + ":" + message, ConsoleColor.White);ShowText3(message);//socket.Send(Encoding.UTF8.GetBytes("服务器收到消息"));}catch (Exception){Action ac = () => { button1.Enabled = true; };//count--;//Console.WriteLine(clientipe + "断开连接" + (count), ConsoleColor.Red);}}if (socket != null && IsSocketConnected(socket)){socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMsg), socket);}}/// 另一种判断connected的方法,但未检测对端网线断开或ungraceful的情况public bool IsSocketConnected(Socket s){#region 过程if (s == null)return false;return !((s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)) || !s.Connected);#endregion}void ReceiveCallback(IAsyncResult result){Socket ts = (Socket)result.AsyncState;ts.EndReceive(result);result.AsyncWaitHandle.Close();ShowText3(string.Format("收到消息:{0}", Encoding.ASCII.GetString(buffer)));//清空数据,重新开始异步接收buffer = new byte[buffer.Length];ts.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ts);}private void ShowText3(string s){Action ac = () => {textBox3.AppendText(s +"\r\n");};Invoke(ac);}private void ShowText4(string s){Action ac = () =>{textBox4.AppendText(s + "\r\n");};Invoke(ac);}private void button2_Click(object sender, EventArgs e){if (socketsend != null && IsSocketConnected(socketsend)){//同步//socket.Send(Encoding.Default.GetBytes(textBox4.Text));//异步byte[] byteData = Encoding.Default.GetBytes(textBox4.Text);socketsend.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), socketsend);}}public void SendCallback(IAsyncResult Iay){Socket handler = (Socket)Iay.AsyncState;// Complete sending the data to the remote device. int bytesSent= handler.EndSend(Iay);ShowText3(string.Format("发送了 {0} 字节到客户端.", bytesSent));//handler.Shutdown(SocketShutdown.Both);//handler.Close();}

下载地址:Sock异步通信(客户端和服务端).zip-C#代码类资源-CSDN下载

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。