Socket异步通信的时候,如何分步读取客户端发送过来的数据?比如“001288888888”假设这个是客户端发送过来的数据,前四位表示整个字符串长度,服务端在异步接收数据的时候,希望能够先接收“0012”这样我就能够知道发送的数据长度,然后再接收下面8位长度数据“88888888”,可是在异步接收数据的时候我不知道如何实现这样的接收方式,我对这块接触不深,我的账户因为前段时间账户被盗了没有什么积分了,希望各位高手不要介意分数的多少,帮小弟解决下这个问题,万分感谢!
调试欢乐多
int index = 0;
int byte_len = 4096;//每次接收缓冲区大小
while (index < len)
{
if(//可添加超时处理)
return;byte[] _b = new byte[byte_len];
count = Stream.Read(_b, 0, byte_len);//TcpClient.GetStream()链接stream读出数据,数据合并省略
if (count > 0)
index += count;
}
服务端:
IPAddress ip = IPAddress.Parse(server_ip);
//用指定ip和端口号初始化
tcplisener = new IPEndPoint(ip, port);
//创建一个socket对象
read = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
read.Bind(tcplisener); //绑定
///收到客户端的连接,建立新的socket并接受信息
read.Listen(500); //开始监听
textBox1.Text = " 等待客户端连接";
accept = new Thread(new ThreadStart(Listen));
accept.Start();
// Listen();
GC.Collect();
GC.WaitForPendingFinalizers();下面是接受请求,处理数据的代码:
public void Listen()
{
//Thread.CurrentThread.IsBackground = true; //后台线程
try
{
while (true)
{
AcceptDone.Reset();
//Socket temp_socket = read.Accept();
read.BeginAccept(new AsyncCallback(AcceptCallback), read); //异步调用
AcceptDone.WaitOne();
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
} public void AcceptCallback(IAsyncResult ar) //accpet的回调处理函数
{
AcceptDone.Set();
Socket temp_socket = (Socket)ar.AsyncState;
Socket client = temp_socket.EndAccept(ar); //获取远程的客户端 textBox1.Text = "建立连接";
IPEndPoint remotepoint = (IPEndPoint)client.RemoteEndPoint;//获取远程的端口
string remoteaddr = remotepoint.Address.ToString(); //获取远程端口的ip地址
textBox1.Text = "接收来自" + remoteaddr + "的连接"; StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); //这里是接收消息的 我的想法是不管任何时候只要一有数据连接我就先只接收该数据的前四个字节,然后再根据这四个直接里面表示的大小接收下面的但是在这里貌似不可以实现我要的功能
} /// </summary>
public void ReadCallback(IAsyncResult ar)
{
String content = String.Empty; // Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket; // Read data from the client socket.
int bytesRead = handler.EndReceive(ar); if (bytesRead > 0)
{
string contentstr = ""; //接收到的数据
contentstr += Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
richTextBox1.Text = contentstr;
byte[] byteData = Encoding.ASCII.GetBytes("Success:" + contentstr);//回发信息
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}如果有高手愿意提供Demo的话,小弟万分感谢!