问题描述
请注意一个问题是关于只在插座使用异步回调模式!
我想建立一个TCP客户端在接收到数据包会通知我,当我套接字被关闭,因为NET提供带beginRecv的feautures,endRecv不连接是否仍然可用通知。
I want to build a TCP client that will notify me when a packet is received and when i the socket is being closed,because the feautures that NET offers with beginRecv,endRecv doesn't inform if the connection is still available.
我的问题:
是不是有一种方法来创建一个TCP客户端就像使用WinAPI的?
My question:Isn't there a way to create a TCP client much like using WinAPI?
我的意思是调用WSAAsyncSelect一条消息,当接收到消息,它调用你叫WSAAsyncSelect功能,然后就可以看到连接是否被关闭或有通过WParams FD_CLOSE FD_READ FD_WRITE一个新的数据包。
I mean calling WSAAsyncSelect with a message,when the message is received it calls the function you've called in WSAAsyncSelect and then you can see whether the connection is closed or there's a new packet through the WParams FD_CLOSE FD_READ FD_WRITE.
如果有我isn't.Can't控制自己的同时连接,我的传入数据包?我不想叫BeginRecv EndRecv所有的时间。 -.-
If there isn't.Can't I control my connection and my incoming packets at the same time? I don't want to call BeginRecv EndRecv all the time. -.-
在此先感谢!
推荐答案
如果你传递一个状态对象,其中包括到你的插座参考,您将有机会获得插座本身。
If you pass a state object which includes a reference to your socket, You'll have access to the socket itself.
public class SocketState
{
public SocketState(Socket s)
{
this._socket = s;
}
private Socket _socket;
public Socket Socket
{
get{return _socket;}
}
}
void SomeFunction()
{
//do some stuff in your code
SocketState stateObject = new SocketState(mySocket);
mySocket.BeginReceive(buffer, offset, size, flags, CallBack, stateObject);
//do some other stuff
}
public void CallBack(IAsyncResult result)
{
SocketState state = (SocketState)result.AsyncState;
state.Socket.EndReceive(result);
//do stuff with your socket.
if(state.Socket.Available)
mySocket.BeginReceive(buffer, offset, size, flags, CallBack, state);
}
这篇关于TCP客户端异步套接字回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!