Reputation: 8271
I'm rewriting an ancient VB6 program in C# (.Net Framework 4.0). It communicates with a piece of industrial equipment on the factory floor. VB6 used some old COM-based socket software; I'm using the .Net Socket class.
When I send a message to the equipment I expect a response back so I know to listen for one then. But the equipment can also send messages asynchronously without warning (say, to indicate a failure or problem). So I always have to receive those. So what I'd really like is an event handler that gets called whenever anything comes in from the equipment.
The Socket class seems to use a BeginReceive/EndReceive scheme for receive event handling. Can I just do a BeginReceive once at the start of my program to define an event-handler for all incoming messages, or do I have to constantly be doing BeginReceive/EndReceive's throughout my program?
Thanks in advance for clarifying the correct way to do this.
Upvotes: 17
Views: 27535
Reputation: 8168
Are you the server?
If you are the server, you will listen for a socket connection, and then accept the socket connection and store it. You will then call BeginReceive
with the stored socket. In the BeginReceive
method, you will provide a callback function to receive, and handle the data.
Once you receive data, the callback happens. The callback function will call EndReceive
on the stored connection. This is where you get/handle the data. You will also call BeginReceive
again to wait for more data.
This way, the BeginReceive
and EndReceive
will run in a circle: you are always receiving data, and waiting for more data.
void WaitForData(SocketState state)
{
try
{
state.Socket.BeginReceive(state.DataBuffer, 0, state.DataBuffer.Length, SocketFlags.None, new AsyncCallback(ReadDataCallback), state);
}
catch (SocketException se)
{
//Socket has been closed
//Close/dispose of socket
}
}
public void ReadDataCallback(IAsyncResult ar)
{
SocketState state = (SocketState)ar.AsyncState;
try
{
// Read data from the client socket.
int iRx = state.Socket.EndReceive(ar);
//Handle Data....
WaitForData(state);
}
catch (ObjectDisposedException)
{
//Socket has been closed
//Close/dispose of socket
}
catch (SocketException)
{
//Socket exception
//Close/dispose of socket
}
}
EDIT: As per your comment, here is an example of a C# asynchronous client: http://msdn.microsoft.com/en-us/library/bbx2eya8.aspx.
The BeginReceive
/EndReceive
work similar to the server.
Upvotes: 14