C#套接字编程,用TcpClient接收服务端的套接字,那怎么给它实现一个接收信息的回调函数啊?
答案:2 悬赏:20
解决时间 2021-02-07 13:06
- 提问者网友:放荡不羁
- 2021-02-07 03:28
C#套接字编程,用TcpClient接收服务端的套接字,那怎么给它实现一个接收信息的回调函数啊?
最佳答案
- 二级知识专家网友:茫然不知崩溃
- 2021-02-07 04:39
你的程序里NetworkStream 放到while外 。服务只侦听。不需要主动去连接客户端。所以不用 BeginConnect。可以异步读BeginRead
byte[] buffer=new byte[1024];
streamClient.BeginRead(buffer, 0, BufferSize, callBack, null);
回调方法:
private void OnReadComplete(IAsyncResult ar)
{
int bytesRead = 0;
try
{
lock (streamToClient)
{
bytesRead = streamToClient.EndRead(ar);
}
if (bytesRead == 0) throw new Exception("读取到0字节");
string msg = Encoding.UTF8.GetString(buffer, 0, bytesRead);
//msg为接收到的信息
}
// 再次调用BeginRead()
lock (streamToClient)
{
AsyncCallback callBack = new AsyncCallback(OnReadComplete);
streamClient.BeginRead(buffer, 0, BufferSize, callBack, null);
}
}
catch (Exception ex)
{
if (streamToClient != null)
streamClient.Dispose();
client.Close();
}
}
byte[] buffer=new byte[1024];
streamClient.BeginRead(buffer, 0, BufferSize, callBack, null);
回调方法:
private void OnReadComplete(IAsyncResult ar)
{
int bytesRead = 0;
try
{
lock (streamToClient)
{
bytesRead = streamToClient.EndRead(ar);
}
if (bytesRead == 0) throw new Exception("读取到0字节");
string msg = Encoding.UTF8.GetString(buffer, 0, bytesRead);
//msg为接收到的信息
}
// 再次调用BeginRead()
lock (streamToClient)
{
AsyncCallback callBack = new AsyncCallback(OnReadComplete);
streamClient.BeginRead(buffer, 0, BufferSize, callBack, null);
}
}
catch (Exception ex)
{
if (streamToClient != null)
streamClient.Dispose();
client.Close();
}
}
全部回答
- 1楼网友:荒唐后生
- 2021-02-07 05:34
客户端想服务端发送socket流 服务端获取流 然后双方通过tcp协议规则信息通信
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯