Tcp异步接收发送

展开阅读全文

TCP服务端异步接收的一个奇怪问题

09-27

刚写了一个使用TCPListener的异步服务端,并使用TCP调试助手作为客户端进行连接和发数,运行时出现了以下现象:rn1.服务端启动、监听端口正常,使用客户端(调试助手)向服务端请求连接也正常,但若发送一个短的数据到服务端,如十六进制的01等等,服务端无响应;若再次发一个数据,如十六进制的01,则服务端显示0102;rn2.上述步骤进行后,再次发送一个短数据,如十六进制的04,服务端响应又正确了。rn3.重新启动服务端、客户端,并再次进行连接,若是发送一个长的数据到服务端,如十六进制的010203040……等等的一起发,则服务器响应并显示相应的接受数据。rnrnrn为什么连接后第一次服务器对客户端发送来的短数据无响应,其后又正常?rnrn代码如下:rnrn[code=C#]rnusing System;rnusing System.Collections.Generic;rnusing System.Linq;rnusing System.Text;rnusing System.Net;rnusing System.Net.Sockets;rnusing System.IO;rnusing System.Threading;rnnamespace ConsoleApplication17rnrn class Servrn rn IPAddress ip;rn IPEndPoint endPoint;rn TcpListener serv;rn private bool key=false;rn byte[] result = new byte[1024] ;rn public ManualResetEvent manualResetEvent = new ManualResetEvent(false);rn public Serv()rn rn ip = IPAddress.Parse("192.168.0.5");rn endPoint = new IPEndPoint(ip, 8000);rn serv = new TcpListener(endPoint);rn rn public bool SetKey//设置服务器运行状态,key为false时断开rn rn setrn rn this.key=value;rn rn rn public void startListen()//开始监听rn rn serv.Start();rn manualResetEvent.Reset();rn serv.BeginAcceptTcpClient(new AsyncCallback(RecvCallBack), serv);rn manualResetEvent.WaitOne();rn rnrn private void RecvCallBack(IAsyncResult ar)//Accept回调方法rn rn TcpClient tcpRecv = serv.EndAcceptTcpClient(ar);rn NetworkStream nStream = tcpRecv.GetStream();rn if (key)rn rn serv.Stop();rn return;rn rn serv.BeginAcceptTcpClient(new AsyncCallback(RecvCallBack), serv);rn nStream.BeginRead(result, 0, result.Length, new AsyncCallback(DoRecvCallBack), nStream);rn manualResetEvent.Set();rn rnrn private void DoRecvCallBack(IAsyncResult ar)//NetWorkStream.beginread回调方法rn rn NetworkStream netStream = ar.AsyncState as NetworkStream;rn if (netStream == null)rn rn return;rn rn int count = 0;rn tryrn rn count = netStream.EndRead(ar);rn netStream.BeginRead(this.result, 0, this.result.Length, new AsyncCallback(this.DoRecvCallBack), netStream);rn rn catchrn rn rn if (count == 0)rn rn return;rn rn string res = "";rn for (int i = 0; i < count; i++)rn rn byte[] b = result[i], (byte)0, (byte)0, (byte)0 ;rn int curData = BitConverter.ToInt32(b, 0);rn res += curData.ToString("x");rn rn Console.WriteLine(DateTime.Now.ToString() + " " + res);rn rn rnrn[/code]rnrn[code=C#]rnusing System;rnusing System.Collections.Generic;rnusing System.Linq;rnusing System.Text;rnusing System.Threading;rnrnrnnamespace ConsoleApplication17rnrn class Programrn rn static void Main(string[] args)rn rn Console.WriteLine("服务器程序已启动");rn bool close=false;rn Serv sv = new Serv();rn sv.SetKey = false;rn Thread t = new Thread(new ThreadStart(sv.startListen));rn t.Start();//启动服务端rn while (!close)//监测用户指令rn rn ConsoleKeyInfo ki = Console.ReadKey();rn if (ki.Key == ConsoleKey.Q)rn rn close = true;rn sv.SetKey = true;rn sv.manualResetEvent.Set();rn rn rn Console.WriteLine();rn Console.WriteLine("程序关闭");rn Console.ReadKey();rn rn rnrn[/code]rnrnrnrn 论坛

Socket异步发送接收结构的问题!

12-31

客户端 结构经过序列化后发送,服务器端接收不到信息!有做过的么,给点意见。rnrnrn Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)rn Dim content As [String] = [String].Emptyrnrn ' Retrieve the state object and the handler socketrn ' from the asynchronous state object.rn Dim state As StateObject = CType(ar.AsyncState, StateObject)rn Dim handler As Socket = state.workSocketrnrn ' Read data from client socket. rn Dim bytesRead As Integer = handler.EndReceive(ar)rnrn If bytesRead > 0 Thenrn ' There might be more data, so store the data received so far.rn state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, _rn bytesRead))rnrn ' Check for end-of-file tag. If it is not there, read rn ' more data.rn content = state.sb.ToString()rn Debug.WriteLine(content)rn If content.IndexOf(vbCr) > -1 Thenrn ' All the data has been read from the rn ' client. Display it on the console.rn Dim _Header As New clsHeaderrn _Header = ByteAToObject(state.buffer)rn Debug.WriteLine(_Header.CommandID)rn Debug.WriteLine(_Header.MessageLength)rn Debug.WriteLine(_Header.SequenceNumber)rnrn Console.WriteLine("Read 0 bytes from socket. " + _rn ControlChars.Cr + " Data : 1", content.Length, content)rn ' Echo the data back to the client.rn 'Send(handler, content)rn Elsern ' Not all data received. Get more.rn handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, _rn 0, New AsyncCallback(AddressOf ReadCallback), state)rn End Ifrn End Ifrn End Sub 'ReadCallbackrn 论坛

没有更多推荐了,返回首页