TCP client Asynchronous socket callback

…衆ロ難τιáo~ 提交于 2019-12-31 05:19:05

问题


Please note the question is about using an asynchronous callback mode only on sockets!

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.

My question: Isn't there a way to create a TCP client much like using WinAPI?

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.

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. -.-

Thanks in advance!


回答1:


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);
}



回答2:


Your question is not really clear. By the tone of your question, it seems like you don't want to do any extra work. You can't do async without some extra work.

The best approach is to use the Asynchronous API from Microsoft, using BeginReceive/EndReceive. These will call your callbacks when the socket is closed. However, you cannot easily use the IO Stream support in .NET by doing this, so there is some extra work involved.

If you want more control, you have to do more work. That's all there is to it.




回答3:


You could also write a simple threaded version to monitor the socket and give you the events and call the callbacks.

Server type code

Simple Socket code



来源:https://stackoverflow.com/questions/686618/tcp-client-asynchronous-socket-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!