I feel, that I am misunderstanding something about async sockets in .Net. The situation is as follows : I have 1 async socket client and 1 async socket server. They communicate without any visible problems, but when I close listener and disconnect clients, the "OnConnectRequest" which is bound to "BeginAccept" as a callback, still gets called at least once. The "BeginReceive", "OnConnectRequest", "Disconnect" and "Dispose" methods are :
public void BeginReceive()
{
_listener.Bind(_endpoint);
_listener.Listen(_maxConnections);
try
{
_listener.BeginAccept(new AsyncCallback(OnConnectRequest), _listener);
}
catch (SocketException se)
{
OnListeningError(this, new Exception("Server cannot accept connections due to network shutdown or some fatal failure", se));
}
}
protected void OnConnectRequest(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket client = listener.EndAccept(ar);
var remoteEndpoint = client.RemoteEndPoint;
IDuplexStateObject state = new DuplexStateObject();
state.WorkSocket = client;
if (_clients.Count <= _maxConnections)
{
lock (_clients)
{
_clients.Add(state);
}
OnConnected(this, state);
}
else
{
//denying connection
client.Close();
AcceptingError(this, null, new Exception(string.Format("Maximal connection count reached, connection attempt {0} has been denied", (remoteEndpoint != null) ? remoteEndpoint.ToString() : null)));
}
//accept connections from other clients
try
{
listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
}
catch (SocketException se)
{
if (se.SocketErrorCode == SocketError.TooManyOpenSockets)
{
OnListeningError(this, new Exception("Maximal connection count reached, not possible to create any more connections"));
}
else
{
OnListeningError(this, new Exception("Server cannot accept connections due to network shutdown or some fatal failure"));
}
}
}
public void Disconnect(IStateObject state)
{
if (state.WorkSocket == null)
{
//OnDisconnectError(this, state.ClientInfo,
// new Exception("No underlying work socket found for client. Already disconnected, disposing connection..."));
OnDisconnected(this, state.ClientInfo);
return;
}
try
{
if (state.WorkSocket.Connected)
{
state.WorkSocket.Shutdown(SocketShutdown.Both);
}
state.WorkSocket.Close();
}
catch (SocketException se)
{
OnDisconnectError(this, state.ClientInfo, se);
}
OnDisconnected(this, state.ClientInfo);
lock (_clients)
{
_clients.Remove(state);
}
}
public void Dispose()
{
_listener.Close();
//keys are cloned before disconnecting
foreach (var client in _clients.ToList())
{
Disconnect(client);
}
}
What I am doing is calling "Dispose" to closes listener and shut down all client sockets. The client is then still active, and it tries to reconnect, but what I expected to happen was server being completely unavailable on corresponding IP and port. What I see instead is "OnConnectRequest" callback being called, which crashes because of attempt to use already disposed socket. Can you please explain, what is wrong here, and how graceful shutdown of a listener and all accepted connections should look like ?
No, this is correct -- the callback you specify in a Begin... operation will always be called, even if you close the socket (if you close the socket, it will be called because of that). You should be catching the ObjectDisposedException you get on the EndAccept and then return without further action. Closing/disposing a socket/listener is the only way to cancel an asynchronous operation on it. (EndAccept can also produce SocketException, which should be handled normally.)
Using a flag you maintain yourself to check if the listener is still available is asking for trouble, because you're introducing shared state that needs to be synchronized (volatile reads and the like). You can easily introduce race conditions that way. The listener already maintains such a flag for you internally, which it uses to throw ObjectDisposedException, so I'd just use that. It's true that under normal circumstances catching ObjectDisposedException is a possible sign of a coding error (since you're supposed to know when an object is disposed), but with asynchronous code it's pretty standard.
Related
I am working on creating a custom TCP/IP client/server application, and have run into a snag when attempting to stop the server. Originally, my code used one TcpListener to listen on a designated port, and my (simplified for convenience) code to start and stop the server went as follows:
private bool state;
private TcpListener listener;
private CancellationTokenSource tokenSource;
private Dictionary<string, ConnectedClient> clients;
private List<Task> clientTasks;
private ConnectedClient command_client;
public async Task RunServer() {
if (!state) {
state = true;
tokenSource = new CancellationTokenSource();
listener = new TcpListener(IPAddress.Any, 55001);
listener.Start();
while (true) {
try {
TcpClient socketClient = await listener.AcceptTcpClientAsync();
ConnectedClient client = new ConnectedClient(socketClient);
clients.Add(client.id, client);
client.task = ProcessClientAsync(client, tokenSource.Token);
clientTasks.Add(client.task);
}
catch (ObjectDisposedException) {
//Server stopped by user
//exit while
break;
}
}
/* Server has been stopped; close all connections */
CloseAll();
}
else {
/* Stop the server */
tokenSource.Cancel();
listener.Stop();
/* Clean up of currently connected clients is handled in CloseAll, handled upon ObjectDisposedException above */
}
}
ConnectedClient is a class I wrote to hold some info about individual clients for convenience and has a function that handles what happens when data is received. I realize I left some things out to streamline, but this code does exactly what I want it to do: the server waits for connections, creates a ConnectedClient object to handle connections received, and goes back to waiting. When this function is called when the server is already listening, the listener is stopped, which causes the listener to throw an exception, which breaks the loop and closes all connections.
The snag occurs when I attempted to create a server that listens on two different ports, which need to be treated differently.
Here is my code for (attempting) that:
private bool state;
private Dictionary<string, ConnectedClient> clients;
private TcpListener command_listener;
private TcpListener query_listener;
private CancellationTokenSource tokenSource;
private List<Task> clientTasks;
public async Task RunServer() {
if (!state) {
state = true;
tokenSource = new CancellationTokenSource();
command_listener = new TcpListener(IPAddress.Any, 55001);
command_listener.Start();
query_listener = new TcpListener(IPAddress.Any, 55002);
query_listener.Start();
Task prevCommand = null;
Task prevQuery = null;
while (true) {
try {
if (prevCommand == null || prevCommand.IsCompleted) {
prevCommand = waitForConnections(command_listener);
}
if (prevQuery == null || prevQuery.IsCompleted) {
prevQuery = waitForConnections(query_listener);
}
await Task.WhenAny(prevCommand, prevQuery);
}
catch (ObjectDisposedException) {
//Server stopped by user
//exit while
break;
}
}
/* Server has been stopped; close all connections */
CloseAll();
}
else {
/* Stop the server */
tokenSource.Cancel();
command_listener.Stop();
query_listener.Stop();
/* Clean up of currently connected clients is handled in CloseAll, handled upon ObjectDisposedException above */
}
}
The purpose of waitForConnections is to handle connection requests so that waiting for a connection on one port doesn't block connections on the other, and also to ensure that only one connection can be made on port 55001.
public async Task waitForConnections(TcpListener listener) {
TcpClient socketClient = await listener.AcceptTcpClientAsync();
if (((IPEndPoint)listener.LocalEndpoint).Port == 55001 ) {
if (command_client == null) {
command_client = new ConnectedClient(socketClient, onClientUpdate, onResend);
clients.Add(command_client.id, command_client);
command_client.task = ProcessClientAsync(command_client, tokenSource.Token);
clientTasks.Add(command_client.task);
}
else {
//only one client allowed on this port, reject the connection
socketClient.Close();
}
}
else {
ConnectedClient client = new ConnectedClient(socketClient, onClientUpdate, onResend);
clients.Add(client.id, client);
client.task = ProcessClientAsync(client, tokenSource.Token);
clientTasks.Add(client.task);
}
}
With this, I am able to connect clients on the two ports without blocking, but calling this function again and stopping the listeners does not seem to cause a ObjectDisposedException to be thrown as expected, which causes the whole program to hang and not do anything. I suspect this is being caused by some irresponsible use of asynchronous functions, but how can I fix it?
Because the await listener.AcceptTcpClientAsync() call is inside an async task instead of directly inside the loop, the exception that occurs when the listener is stopped causes the task to return with a status of "Faulted". Because the exception isn't caught, the loop continues, and a faulted task is considered a completed task, so it goes right back to trying to listen for connections despite the stopped listener (which in turn most likely causes the task to fault again).
Could have fixed this by checking for faulted tasks instead of catching the exception, but I instead chose to set a flag when I try to stop the server that breaks the loop and allows the program to close connections as intended.
I feel, that I am misunderstanding something about async sockets in .Net. The situation is as follows : I have 1 async socket client and 1 async socket server. They communicate without any visible problems, but when I close listener and disconnect clients, the "OnConnectRequest" which is bound to "BeginAccept" as a callback, still gets called at least once. The "BeginReceive", "OnConnectRequest", "Disconnect" and "Dispose" methods are :
public void BeginReceive()
{
_listener.Bind(_endpoint);
_listener.Listen(_maxConnections);
try
{
_listener.BeginAccept(new AsyncCallback(OnConnectRequest), _listener);
}
catch (SocketException se)
{
OnListeningError(this, new Exception("Server cannot accept connections due to network shutdown or some fatal failure", se));
}
}
protected void OnConnectRequest(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket client = listener.EndAccept(ar);
var remoteEndpoint = client.RemoteEndPoint;
IDuplexStateObject state = new DuplexStateObject();
state.WorkSocket = client;
if (_clients.Count <= _maxConnections)
{
lock (_clients)
{
_clients.Add(state);
}
OnConnected(this, state);
}
else
{
//denying connection
client.Close();
AcceptingError(this, null, new Exception(string.Format("Maximal connection count reached, connection attempt {0} has been denied", (remoteEndpoint != null) ? remoteEndpoint.ToString() : null)));
}
//accept connections from other clients
try
{
listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
}
catch (SocketException se)
{
if (se.SocketErrorCode == SocketError.TooManyOpenSockets)
{
OnListeningError(this, new Exception("Maximal connection count reached, not possible to create any more connections"));
}
else
{
OnListeningError(this, new Exception("Server cannot accept connections due to network shutdown or some fatal failure"));
}
}
}
public void Disconnect(IStateObject state)
{
if (state.WorkSocket == null)
{
//OnDisconnectError(this, state.ClientInfo,
// new Exception("No underlying work socket found for client. Already disconnected, disposing connection..."));
OnDisconnected(this, state.ClientInfo);
return;
}
try
{
if (state.WorkSocket.Connected)
{
state.WorkSocket.Shutdown(SocketShutdown.Both);
}
state.WorkSocket.Close();
}
catch (SocketException se)
{
OnDisconnectError(this, state.ClientInfo, se);
}
OnDisconnected(this, state.ClientInfo);
lock (_clients)
{
_clients.Remove(state);
}
}
public void Dispose()
{
_listener.Close();
//keys are cloned before disconnecting
foreach (var client in _clients.ToList())
{
Disconnect(client);
}
}
What I am doing is calling "Dispose" to closes listener and shut down all client sockets. The client is then still active, and it tries to reconnect, but what I expected to happen was server being completely unavailable on corresponding IP and port. What I see instead is "OnConnectRequest" callback being called, which crashes because of attempt to use already disposed socket. Can you please explain, what is wrong here, and how graceful shutdown of a listener and all accepted connections should look like ?
No, this is correct -- the callback you specify in a Begin... operation will always be called, even if you close the socket (if you close the socket, it will be called because of that). You should be catching the ObjectDisposedException you get on the EndAccept and then return without further action. Closing/disposing a socket/listener is the only way to cancel an asynchronous operation on it. (EndAccept can also produce SocketException, which should be handled normally.)
Using a flag you maintain yourself to check if the listener is still available is asking for trouble, because you're introducing shared state that needs to be synchronized (volatile reads and the like). You can easily introduce race conditions that way. The listener already maintains such a flag for you internally, which it uses to throw ObjectDisposedException, so I'd just use that. It's true that under normal circumstances catching ObjectDisposedException is a possible sign of a coding error (since you're supposed to know when an object is disposed), but with asynchronous code it's pretty standard.
How can I detect that a client has disconnected from my server?
I have the following code in my AcceptCallBack method
static Socket handler = null;
public static void AcceptCallback(IAsyncResult ar)
{
//Accept incoming connection
Socket listener = (Socket)ar.AsyncState;
handler = listener.EndAccept(ar);
}
I need to find a way to discover as soon as possible that the client has disconnected from the handler Socket.
I've tried:
handler.Available;
handler.Send(new byte[1], 0,
SocketFlags.None);
handler.Receive(new byte[1], 0,
SocketFlags.None);
The above approaches work when you are connecting to a server and want to detect when the server disconnects but they do not work when you are the server and want to detect client disconnection.
Any help will be appreciated.
Since there are no events available to signal when the socket is disconnected, you will have to poll it at a frequency that is acceptable to you.
Using this extension method, you can have a reliable method to detect if a socket is disconnected.
static class SocketExtensions
{
public static bool IsConnected(this Socket socket)
{
try
{
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}
catch (SocketException) { return false; }
}
}
Someone mentioned keepAlive capability of TCP Socket.
Here it is nicely described:
http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html
I'm using it this way: after the socket is connected, I'm calling this function, which sets keepAlive on. The keepAliveTime parameter specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent. The keepAliveInterval parameter specifies the interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received.
void SetKeepAlive(bool on, uint keepAliveTime, uint keepAliveInterval)
{
int size = Marshal.SizeOf(new uint());
var inOptionValues = new byte[size * 3];
BitConverter.GetBytes((uint)(on ? 1 : 0)).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)keepAliveTime).CopyTo(inOptionValues, size);
BitConverter.GetBytes((uint)keepAliveInterval).CopyTo(inOptionValues, size * 2);
socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
I'm also using asynchronous reading:
socket.BeginReceive(packet.dataBuffer, 0, 128,
SocketFlags.None, new AsyncCallback(OnDataReceived), packet);
And in callback, here is caught timeout SocketException, which raises when socket doesn't get ACK signal after keep-alive packet.
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
int iRx = socket.EndReceive(asyn);
}
catch (SocketException ex)
{
SocketExceptionCaught(ex);
}
}
This way, I'm able to safely detect disconnection between TCP client and server.
This is simply not possible. There is no physical connection between you and the server (except in the extremely rare case where you are connecting between two compuers with a loopback cable).
When the connection is closed gracefully, the other side is notified. But if the connection is disconnected some other way (say the users connection is dropped) then the server won't know until it times out (or tries to write to the connection and the ack times out). That's just the way TCP works and you have to live with it.
Therefore, "instantly" is unrealistic. The best you can do is within the timeout period, which depends on the platform the code is running on.
EDIT:
If you are only looking for graceful connections, then why not just send a "DISCONNECT" command to the server from your client?
"That's just the way TCP works and you have to live with it."
Yup, you're right. It's a fact of life I've come to realize. You will see the same behavior exhibited even in professional applications utilizing this protocol (and even others). I've even seen it occur in online games; you're buddy says "goodbye", and he appears to be online for another 1-2 minutes until the server "cleans house".
You can use the suggested methods here, or implement a "heartbeat", as also suggested. I choose the former. But if I did choose the latter, I'd simply have the server "ping" each client every so often with a single byte, and see if we have a timeout or no response. You could even use a background thread to achieve this with precise timing. Maybe even a combination could be implemented in some sort of options list (enum flags or something) if you're really worried about it. But it's no so big a deal to have a little delay in updating the server, as long as you DO update. It's the internet, and no one expects it to be magic! :)
Implementing heartbeat into your system might be a solution. This is only possible if both client and server are under your control. You can have a DateTime object keeping track of the time when the last bytes were received from the socket. And assume that the socket not responded over a certain interval are lost. This will only work if you have heartbeat/custom keep alive implemented.
I've found quite useful, another workaround for that!
If you use asynchronous methods for reading data from the network socket (I mean, use BeginReceive - EndReceive methods), whenever a connection is terminated; one of these situations appear: Either a message is sent with no data (you can see it with Socket.Available - even though BeginReceive is triggered, its value will be zero) or Socket.Connected value becomes false in this call (don't try to use EndReceive then).
I'm posting the function I used, I think you can see what I meant from it better:
private void OnRecieve(IAsyncResult parameter)
{
Socket sock = (Socket)parameter.AsyncState;
if(!sock.Connected || sock.Available == 0)
{
// Connection is terminated, either by force or willingly
return;
}
sock.EndReceive(parameter);
sock.BeginReceive(..., ... , ... , ..., new AsyncCallback(OnRecieve), sock);
// To handle further commands sent by client.
// "..." zones might change in your code.
}
This worked for me, the key is you need a separate thread to analyze the socket state with polling. doing it in the same thread as the socket fails detection.
//open or receive a server socket - TODO your code here
socket = new Socket(....);
//enable the keep alive so we can detect closure
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
//create a thread that checks every 5 seconds if the socket is still connected. TODO add your thread starting code
void MonitorSocketsForClosureWorker() {
DateTime nextCheckTime = DateTime.Now.AddSeconds(5);
while (!exitSystem) {
if (nextCheckTime < DateTime.Now) {
try {
if (socket!=null) {
if(socket.Poll(5000, SelectMode.SelectRead) && socket.Available == 0) {
//socket not connected, close it if it's still running
socket.Close();
socket = null;
} else {
//socket still connected
}
}
} catch {
socket.Close();
} finally {
nextCheckTime = DateTime.Now.AddSeconds(5);
}
}
Thread.Sleep(1000);
}
}
The example code here
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx
shows how to determine whether the Socket is still connected without sending any data.
If you called Socket.BeginReceive() on the server program and then the client closed the connection "gracefully", your receive callback will be called and EndReceive() will return 0 bytes. These 0 bytes mean that the client "may" have disconnected. You can then use the technique shown in the MSDN example code to determine for sure whether the connection was closed.
Expanding on comments by mbargiel and mycelo on the accepted answer, the following can be used with a non-blocking socket on the server end to inform whether the client has shut down.
This approach does not suffer the race condition that affects the Poll method in the accepted answer.
// Determines whether the remote end has called Shutdown
public bool HasRemoteEndShutDown
{
get
{
try
{
int bytesRead = socket.Receive(new byte[1], SocketFlags.Peek);
if (bytesRead == 0)
return true;
}
catch
{
// For a non-blocking socket, a SocketException with
// code 10035 (WSAEWOULDBLOCK) indicates no data available.
}
return false;
}
}
The approach is based on the fact that the Socket.Receive method returns zero immediately after the remote end shuts down its socket and we've read all of the data from it. From Socket.Receive documentation:
If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.
If you are in non-blocking mode, and there is no data available in the protocol stack buffer, the Receive method will complete immediately and throw a SocketException.
The second point explains the need for the try-catch.
Use of the SocketFlags.Peek flag leaves any received data untouched for a separate receive mechanism to read.
The above will work with a blocking socket as well, but be aware that the code will block on the Receive call (until data is received or the receive timeout elapses, again resulting in a SocketException).
Above answers can be summarized as follow :
Socket.Connected properity determine socket state depend on last read or receive state so it can't detect current disconnection state until you manually close the connection or remote end gracefully close of socket (shutdown).
So we can use the function below to check connection state:
bool IsConnected(Socket socket)
{
try
{
if (socket == null) return false;
return !((socket.Poll(5000, SelectMode.SelectRead) && socket.Available == 0) || !socket.Connected);
}
catch (SocketException)
{
return false;
}
//the above code is short exp to :
/* try
{
bool state1 = socket.Poll(5000, SelectMode.SelectRead);
bool state2 = (socket.Available == 0);
if ((state1 && state2) || !socket.Connected)
return false;
else
return true;
}
catch (SocketException)
{
return false;
}
*/
}
Also the above check need to care about poll respone time(block time)
Also as said by Microsoft Documents : this poll method "can't detect proplems like a broken netwrok cable or that remote host was shut down ungracefuuly".
also as said above there is race condition between socket.poll and socket.avaiable which may give false disconnect.
The best way as said by Microsoft Documents is to attempt to send or recive data to detect these kinds of errors as MS docs said.
The below code is from Microsoft Documents :
// This is how you can determine whether a socket is still connected.
bool IsConnected(Socket client)
{
bool blockingState = client.Blocking; //save socket blocking state.
bool isConnected = true;
try
{
byte [] tmp = new byte[1];
client.Blocking = false;
client.Send(tmp, 0, 0); //make a nonblocking, zero-byte Send call (dummy)
//Console.WriteLine("Connected!");
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
//Console.WriteLine("Still Connected, but the Send would block");
}
else
{
//Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
isConnected = false;
}
}
finally
{
client.Blocking = blockingState;
}
//Console.WriteLine("Connected: {0}", client.Connected);
return isConnected ;
}
//and heres comments from microsoft docs*
The socket.Connected property gets the connection state of the Socket as of the last I/O operation. When it returns false, the Socket was either never connected, or is no longer connected.
Connected is not thread-safe; it may return true after an operation is aborted when the Socket is disconnected from another thread.
The value of the Connected property reflects the state of the connection as of the most recent operation.
If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; //otherwise, the socket is no longer connected .
Can't you just use Select?
Use select on a connected socket. If the select returns with your socket as Ready but the subsequent Receive returns 0 bytes that means the client disconnected the connection. AFAIK, that is the fastest way to determine if the client disconnected.
I do not know C# so just ignore if my solution does not fit in C# (C# does provide select though) or if I had misunderstood the context.
Using the method SetSocketOption, you will be able to set KeepAlive that will let you know whenever a Socket gets disconnected
Socket _connectedSocket = this._sSocketEscucha.EndAccept(asyn);
_connectedSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
http://msdn.microsoft.com/en-us/library/1011kecd(v=VS.90).aspx
Hope it helps!
Ramiro Rinaldi
i had same problem , try this :
void client_handler(Socket client) // set 'KeepAlive' true
{
while (true)
{
try
{
if (client.Connected)
{
}
else
{ // client disconnected
break;
}
}
catch (Exception)
{
client.Poll(4000, SelectMode.SelectRead);// try to get state
}
}
}
This is in VB, but it seems to work well for me. It looks for a 0 byte return like the previous post.
Private Sub RecData(ByVal AR As IAsyncResult)
Dim Socket As Socket = AR.AsyncState
If Socket.Connected = False And Socket.Available = False Then
Debug.Print("Detected Disconnected Socket - " + Socket.RemoteEndPoint.ToString)
Exit Sub
End If
Dim BytesRead As Int32 = Socket.EndReceive(AR)
If BytesRead = 0 Then
Debug.Print("Detected Disconnected Socket - Bytes Read = 0 - " + Socket.RemoteEndPoint.ToString)
UpdateText("Client " + Socket.RemoteEndPoint.ToString + " has disconnected from Server.")
Socket.Close()
Exit Sub
End If
Dim msg As String = System.Text.ASCIIEncoding.ASCII.GetString(ByteData)
Erase ByteData
ReDim ByteData(1024)
ClientSocket.BeginReceive(ByteData, 0, ByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf RecData), ClientSocket)
UpdateText(msg)
End Sub
You can also check the .IsConnected property of the socket if you were to poll.
I was told several times that async is better or that I should use async instead of sync sockets and as such started learning it, but am already having difficult.
I've got the basic feel of how the callback works and how to establish a connection.
I am using this msdn code as reference!
A few problems I am having with the code:
Currently that code will connect to the server, send a text, read the response and exit. How do I do so I can keep receiving the data until either the server disconnects me and/or I end it by myself ? I am not much sure on how I should do it, if I would need to wrap it on a thread with while or simple call that Receive again once the ReceiveCallback is done.
Another things I've noticed is when it connects, the socket is assigned to client but the code itself is always reassigning the client socket which I don't understand very well compared to the sync socket we have a main socket that we are always consulting etc.
I am not sure on how old the reference I am using is but would appreciate if you could help me with examples of what I have pointed out as it is easier for me to understand.
UPDATE:
private void SetupRecieveCallback(Socket sock)
{
new Thread(
delegate()
{
while (isReceiving)
{
_receiveQueue.Reset();
try
{
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock);
}
catch (Exception ex)
{
_logger.Error("Setup Recieve Callback failed! " + ex.Message);
}
_receiveQueue.WaitOne();
}
}
).Start();
/*
// The original code
try
{
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock);
}
catch (Exception ex)
{
_logger.Error("Setup Recieve Callback failed! " + ex.Message);
}
*/
}
Simply call BeginReceive() again in the callback to keep receiving. When the server breaks the connection then your callback will be called and EndReceive() throws an ObjectDisposedException. That's how you know to stop calling BeginReceive().
Second question is harder to decode (ask only one). I'm guessing you are puzzled about this statement:
private static void ConnectCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;
// etc..
No reassigning the socket is happening here. The code simply retrieves a reference to the original socket. Which is a useful technique, it allows this callback to be used by more than one connection. The ar.AsyncState value got to be the socket by this statement:
client.BeginConnect( remoteEP,
new AsyncCallback(ConnectCallback), client);
Note how client is passed to the AsyncCallback constructor. The exact same client that's retrieved in the callback. Any object can be passed.
I have around 5000 modem (thin clients), and I want to communicate with them, one of a my method is like this : string GetModemData(modemID), now I have an open port in server that listens to modem and I'm using socket programming to send data to modems (calling related function), but when i want send data to multiple modem in a same time and get response from them, I don't know what should i do? I can send data to one modem and waiting for its response and then send another data to other modems (sequential), but the problem is client should be wait long time to get answer(may be some different client want to get some information from modems so they all will be wait into the Q or something like this), I think one way to solving this problem is to use multiple port and listen for each modem to related port, but it takes too many ports and also may be memory usage going up and exceed my available memory space, so some lost may be occurred (is this true?). what should to do ? I'd thinking about Parallelism, but i think its not related i should to wait for one port, because i don't know should to pass current received data to which client. I'm using asp.net.
currently I'm doing like this:
private void StartListener()
{
ModemTcpListener = new TcpListener(ModemPort);
//ClientTcpListener = new TcpListener(ClientPort);
ModemTcpListener.Start();
ModemTcpListener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptModemCallback), ModemTcpListener);
}
and in return
private void DoReadModemCallback(IAsyncResult ar)
{
try
{
bool bRet = ar.AsyncWaitHandle.WaitOne(420000);
Modem modem = ar.AsyncState as Modem;
if (!bRet || modem == null)
{
return;
}
}
catch{}
// now send data to which client?????? if i'm going to use async????
}
and :
private void DoAcceptModemCallback(IAsyncResult ar)
{
try
{
ModemTcpListener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptModemCallback), ModemTcpListener);
TcpClient tcpClient = ModemTcpListener.EndAcceptTcpClient(ar);
Modem modem= new Modem(tcpClient, "");
tcpClient.GetStream().BeginRead(modem.Buffer, 0, tcpClient.ReceiveBufferSize, new AsyncCallback(DoReadModemCallback), modem);
ModemTcpListener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptModemCallback), ModemTcpListener);
Log.Write("a Modem connect ...");
}
catch (Exception ex)
{
}
}
Heres an example keeping track of all your clients. I've compacted it for readability. You should really split it up into multiple classes.
I'm using Pool (which I just created and commited) and SimpleServer. Both classes are part of a library that I'm currently building (but far from done).
Don't be afraid of having 5000 sockets open, they do not consume much resources when you are using asynchronous operations.
public class SuperServer
{
private List<ClientContext> _clients = new List<ClientContext>();
private SimpleServer _server;
private Pool<byte[]> _bufferPool;
public SuperServer()
{
// Create a buffer pool to be able to reuse buffers
// since your clients will most likely connect and disconnect
// often.
//
// The pool takes a anonymous function which should return a new buffer.
_bufferPool = new Pool<byte[]>(() => new byte[65535]);
}
public void Start(IPEndPoint listenAddress)
{
_server = new SimpleServer(listenAddress, OnAcceptedSocket);
// Allow five connections to be queued (to be accepted)
_server.Start(5);
}
// you should handle exceptions for the BeginSend
// and remove the client accordingly.
public void SendToAll(byte[] info)
{
lock (_clients)
{
foreach (var client in _clients)
client.Socket.BeginSend(info, 0, info.Length, SocketFlags.None, null, null);
}
}
// Server have accepted a new client.
private void OnAcceptedSocket(Socket socket)
{
var context = new ClientContext();
context.Inbuffer = _bufferPool.Dequeue();
context.Socket = socket;
lock (_clients)
_clients.Add(context);
// this method will eat very few resources and
// there should be no problem having 5000 waiting sockets.
context.Socket.BeginReceive(context.Inbuffer, 0, context.Inbuffer.Length, SocketFlags.None, OnRead,
context);
}
//Woho! You have received data from one of the clients.
private void OnRead(IAsyncResult ar)
{
var context = (ClientContext) ar.AsyncState;
try
{
var bytesRead = context.Socket.EndReceive(ar);
if (bytesRead == 0)
{
HandleClientDisconnection(context);
return;
}
// process context.Inbuffer here.
}
catch (Exception err)
{
//log exception here.
HandleClientDisconnection(context);
return;
}
// use a new try/catch to make sure that we start
// read again event if processing of last bytes failed.
try
{
context.Socket.BeginReceive(context.Inbuffer, 0, context.Inbuffer.Length, SocketFlags.None, OnRead,
context);
}
catch (Exception err)
{
//log exception here.
HandleClientDisconnection(context);
}
}
// A client have disconnected.
private void HandleClientDisconnection(ClientContext context)
{
_bufferPool.Enqueue(context.Inbuffer);
try
{
context.Socket.Close();
lock (_clients)
_clients.Remove(context);
}
catch(Exception err)
{
//log exception
}
}
// One of your modems
// add your own state info.
private class ClientContext
{
public byte[] Inbuffer;
public Socket Socket;
}
}
Used classes:
Pool: http://fadd.codeplex.com/SourceControl/changeset/view/58858#1054902
SimpleServer: http://fadd.codeplex.com/SourceControl/changeset/view/58859#1054893
You need to use the asynchronous tcp/ip methods. This article shows how:
http://www.codeproject.com/KB/IP/asyncsockets.aspx
The critical piece is the BeginReceive() and related callback functions. Any more q's, please leave comments to this answer ;) BEST OF LUCK!
You need multi threading, whenever a client establishes a connection to the server start a new thread for it and start communication send/receive.
Here are some articles explaining multithreading in c#,
c-sharpcorner
codeproject
And here's a sample server application with multithreading,
http://www.dotnetspider.com/resources/2829-A-multi-readed-server-C-which-finds-prime-num.aspx