在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
简单的实现tcp同步和异步,udp,串口通信 static List<TcpClientState> clientArray = new List<TcpClientState>(); static void AsyncTCP(IPEndPoint iep) { TcpListener listener = new TcpListener(iep); listener.Start(); byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 }; listener.Server.IOControl(IOControlCode.KeepAliveValues, inValue, null); #region//异步tcp AsyncCallback dataReceiveAsyncCallback = null; dataReceiveAsyncCallback = ar => { TcpClientState innerclient = (TcpClientState)ar.AsyncState; if ((innerclient.InnerClient == null) || (!innerclient.InnerClient.Connected)) return; NetworkStream stream = innerclient.InnerClient.GetStream(); int num; //异常断开 try { num = stream.EndRead(ar); } catch { num = 0; } if (num < 1)//断开连接 { Console.WriteLine(innerclient.InnerClient.Client.RemoteEndPoint.ToString() + "断开连接"); clientArray.Remove(innerclient); return; } byte[] receivebytes = new byte[num]; Buffer.BlockCopy(innerclient.Buffer, 0, receivebytes, 0, num); string s = Encoding.Default.GetString(receivebytes); Console.WriteLine(s); var data = Encoding.Default.GetBytes(string.Format("收到:{0}", s)); innerclient.InnerClient.GetStream().BeginWrite(data, 0, data.Length, arw => { ((TcpClient)arw.AsyncState).GetStream().EndWrite(arw); },innerclient.InnerClient); stream.BeginRead(innerclient.Buffer, 0, innerclient.Buffer.Length, dataReceiveAsyncCallback, innerclient); }; AsyncCallback connectAsyncCallbackcallback = null; connectAsyncCallbackcallback = ar => { var listen = (TcpListener)ar.AsyncState; TcpClient client = listen.EndAcceptTcpClient(ar); Console.WriteLine(client.Client.RemoteEndPoint.ToString() + "连接成功"); byte[] buf = new byte[client.ReceiveBufferSize]; TcpClientState innerclient = new TcpClientState(client, buf); clientArray.Add(innerclient); NetworkStream netstream = client.GetStream(); netstream.BeginRead(innerclient.Buffer, 0, innerclient.Buffer.Length, dataReceiveAsyncCallback, innerclient); if (connectAsyncCallbackcallback == null) return; listen.BeginAcceptTcpClient(connectAsyncCallbackcallback, ar.AsyncState); }; listener.BeginAcceptTcpClient(connectAsyncCallbackcallback, listener); Console.WriteLine("开始监听"); Console.Read(); #endregion } static void synctcp(IPEndPoint iep) { TcpListener listener = new TcpListener(iep); Console.WriteLine("开始监听"); listener.Start(); byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 }; listener.Server.IOControl(IOControlCode.KeepAliveValues, inValue, null); #region //同步tcp Thread listenThread = new Thread(() => { while (true) { var client = listener.AcceptTcpClient(); Console.WriteLine(client.Client.RemoteEndPoint.ToString() + "连接成功"); Thread datareceiveThread = new Thread(() => { NetworkStream stream = client.GetStream(); while (true) { if (stream.DataAvailable) { byte[] buf = new byte[client.Client.ReceiveBufferSize]; int len = client.Client.Receive(buf); Console.WriteLine(Encoding.Default.GetString(buf, 0, len)); } } }); datareceiveThread.Start(); } }); listenThread.Start(); #endregion } static void udp(IPEndPoint iep) { Socket udpSocket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); udpSocket.Bind(iep); var remotEndPoint = new IPEndPoint(IPAddress.Parse("10.6.179.44"), 10000); Thread thread=new Thread(() => { while (true) { if (udpSocket.Available > 0) { byte[] buf = new byte[udpSocket.Available]; udpSocket.Receive(buf); Console.WriteLine(Encoding.Default.GetString(buf)); udpSocket.SendTo(buf, remotEndPoint); } } }); thread.Start(); Console.WriteLine("wait"); Console.Read(); } static void com(string com, int port) { var m_port = new SerialPort(com, port); m_port.DataReceived += (obj, args) => { int length = m_port.ReadBufferSize; byte[] buf = new byte[length]; m_port.Read(buf, 0, length); string s = Encoding.Default.GetString(buf); Console.WriteLine(s); m_port.Write(buf, 0, buf.Length); }; m_port.Open(); } tcp异步客户端 /// <summary> 连接服务端 /// </summary> /// <param name="ip">服务端IP</param> /// <param name="port">服务端端口</param> static void AsynConnect(string ip, int port) { var serverEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); var _client=new TcpClient(); _client.BeginConnect(serverEndPoint.Address, serverEndPoint.Port, asynresult => { _client.EndConnect(asynresult); Console.WriteLine("连上服务端{0}", _client.Connected); if (_client.Connected) { NetworkStream stream = _client.GetStream(); byte[] buf = new byte[_client.ReceiveBufferSize]; AsyncCallback asyncCallback = null; asyncCallback = asynreadresult => { int num = 0; try { num = stream.EndRead(asynreadresult); } catch(Exception ex) { Console.WriteLine(ex.Message); num = 0; } if (num == 0) { Console.WriteLine("服务端断开"); return; } byte[] receivebytes = new byte[num]; Buffer.BlockCopy(buf, 0, receivebytes, 0, num); Console.WriteLine(Encoding.Default.GetString(receivebytes)); stream.BeginWrite(receivebytes, 0, receivebytes.Length, result => { stream.EndRead(result); }, null); stream.BeginRead(buf, 0, buf.Length, asyncCallback, null); }; stream.BeginRead(buf, 0, buf.Length, asyncCallback, null); } }, _client); Console.Read(); }
|
请发表评论