/// <summary> /// Called when the client has received data or the connection has been closed. /// </summary> /// <param name="ar">the async operation result object from the receive operation</param> private static void OnReceiveHandler(IAsyncResult ar) { if (ar == null) { return; } BaseClient baseClient = null; try { baseClient = (BaseClient)ar.AsyncState; int numBytes = baseClient.Socket.EndReceive(ar); if (numBytes > 0) { baseClient.HasReceivedBytes = true; baseClient.OnReceive(numBytes); baseClient.BeginReceive(); } else { // Only show a message if this client has received bytes in the past // This helps avoid console spam for portal and other 0 byte pings - tolakram if (baseClient.HasReceivedBytes) { if (Log.IsDebugEnabled) { Log.Debug("Disconnecting client (" + baseClient.TcpEndpointAddress + "), received bytes=" + numBytes); } } baseClient._srvr.Disconnect(baseClient); } } catch (ObjectDisposedException) { if (baseClient != null) { baseClient._srvr.Disconnect(baseClient); } } catch (SocketException e) { if (baseClient != null) { if (Log.IsInfoEnabled) { try { Log.Info(string.Format("{0} {1}", baseClient.TcpEndpoint, e.Message)); } catch (SocketException ex) { Log.Info(string.Format("EndPoint not availaible: {0} {1}", e.Message, ex.Message)); } } baseClient._srvr.Disconnect(baseClient); } } catch (Exception e) { if (Log.IsErrorEnabled) { Log.Error("OnReceiveHandler", e); } if (baseClient != null) { baseClient._srvr.Disconnect(baseClient); } } }
/// <summary> /// Called when a client is trying to connect to the server /// </summary> /// <param name="ar">Async result of the operation</param> private void AcceptCallback(IAsyncResult ar) { Socket sock = null; try { if (_listen == null) { return; } sock = _listen.EndAccept(ar); sock.SendBufferSize = Constants.SendBufferSize; sock.ReceiveBufferSize = Constants.ReceiveBufferSize; sock.NoDelay = Constants.UseNoDelay; BaseClient baseClient = null; try { // Removing this message in favor of connection message in GameClient // This will also reduce spam when server is pinged with 0 bytes - Tolakram // string ip = sock.Connected ? sock.RemoteEndPoint.ToString() : "socket disconnected"; // Log.Info("Incoming connection from " + ip); baseClient = GetNewClient(); baseClient.Socket = sock; lock (_clientsLock) { _clients.Add(baseClient); } baseClient.OnConnect(); baseClient.BeginReceive(); } catch (SocketException) { Log.Error("BaseServer SocketException"); if (baseClient != null) { Disconnect(baseClient); } } catch (Exception e) { Log.Error("Client creation", e); if (baseClient != null) { Disconnect(baseClient); } } } catch { Log.Error("AcceptCallback: Catch"); if (sock != null) // don't leave the socket open on exception { try { sock.Close(); } catch { } } } finally { if (_listen != null) { _listen.BeginAccept(_asyncAcceptCallback, this); } } }