Esempio n. 1
0
 private void SafeSocketOperation(string operationName, SocketInfo socketInfo, Action action, Action <Exception> exceptionHandler = null)
 {
     try
     {
         action();
     }
     catch (SocketException ex)
     {
         if (_socketEventListener != null)
         {
             Task.Factory.StartNew(() =>
             {
                 _socketEventListener.OnSocketException(socketInfo, ex);
             });
         }
         if (exceptionHandler != null)
         {
             exceptionHandler(ex);
         }
     }
     catch (ObjectDisposedException)
     {
     }
     catch (Exception ex)
     {
         _logger.Error(
             string.Format("Socket {0} has unknown exception, remoting endpoint address:{1}", operationName,
                           socketInfo.SocketRemotingEndpointAddress), ex);
         if (exceptionHandler != null)
         {
             exceptionHandler(ex);
         }
     }
 }
Esempio n. 2
0
 private void NotifyNewSocketAccepted(SocketInfo socketInfo)
 {
     if (_socketEventListener != null)
     {
         Task.Factory.StartNew(() => _socketEventListener.OnNewSocketAccepted(socketInfo));
     }
 }
Esempio n. 3
0
 public ClientSocket Connect(string address, int port)
 {
     _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     _socket.ReceiveBufferSize = 8192;
     _socket.Connect(address, port);
     _socketInfo = new SocketInfo(_socket);
     return(this);
 }
Esempio n. 4
0
        public void SendMessage(SocketInfo socketInfo, byte[] message, Action <SendResult> messageSentCallback)
        {
            if (message.Length == 0)
            {
                throw new Exception(string.Format("Send message failed, message length cannot be zero, target socket address:{0}",
                                                  socketInfo.SocketRemotingEndpointAddress));
            }
            var wrappedMessage = SocketUtils.BuildMessage(message);

            if (wrappedMessage.Length > 0)
            {
                SafeSocketOperation("BeginSend", socketInfo, () =>
                {
                    socketInfo.InnerSocket.BeginSend(wrappedMessage, 0, wrappedMessage.Length, SocketFlags.None, SendCallback,
                                                     new SendContext(socketInfo, wrappedMessage, messageSentCallback));
                });
            }
        }
Esempio n. 5
0
        public void Start(Action <ReceiveContext> messageReceivedCallback)
        {
            if (_isRunning)
            {
                return;
            }

            _isRunning = true;

            _listenNewClientWorker = new Worker("ServerSocket.AcceptNewClient", () =>
            {
                if (!_isRunning)
                {
                    return;
                }

                _messageReceivedCallback = messageReceivedCallback;
                _newClientSocketSignal.Reset();

                try
                {
                    _socket.BeginAccept(asyncResult =>
                    {
                        if (!_isRunning)
                        {
                            return;
                        }

                        var clientSocket = _socket.EndAccept(asyncResult);
                        var socketInfo   = new SocketInfo(clientSocket);
                        NotifyNewSocketAccepted(socketInfo);
                        _newClientSocketSignal.Set();

                        if (!_isRunning)
                        {
                            return;
                        }

                        _socketService.ReceiveMessage(socketInfo, receivedMessage =>
                        {
                            var receiveContext = new ReceiveContext(socketInfo, receivedMessage, context =>
                            {
                                _socketService.SendMessage(context.ReplySocketInfo, context.ReplyMessage, sendResult =>
                                {
                                    if (context.ReplySentCallback != null)
                                    {
                                        context.ReplySentCallback(sendResult);
                                    }
                                });
                            });
                            _messageReceivedCallback(receiveContext);
                        });
                    }, _socket);
                }
                catch (SocketException socketException)
                {
                    _logger.Error(string.Format("Socket accept exception, ErrorCode:{0}", socketException.SocketErrorCode), socketException);
                }
                catch (Exception ex)
                {
                    _logger.Error("Unknown socket accept exception.", ex);
                }

                if (_isRunning)
                {
                    _newClientSocketSignal.WaitOne();
                }
            });
            _listenNewClientWorker.Start();
        }
Esempio n. 6
0
 public ReceiveContext(SocketInfo replySocketInfo, byte[] receivedMessage, Action <ReceiveContext> messageHandledCallback)
 {
     ReplySocketInfo        = replySocketInfo;
     ReceivedMessage        = receivedMessage;
     MessageHandledCallback = messageHandledCallback;
 }
Esempio n. 7
0
 public ReceiveState(SocketInfo sourceSocket, int receiveSize, Action <byte[]> messageReceivedCallback)
 {
     SourceSocket            = sourceSocket;
     ReceiveSize             = receiveSize;
     MessageReceivedCallback = messageReceivedCallback;
 }
Esempio n. 8
0
 public void ReceiveMessage(SocketInfo sourceSocket, Action <byte[]> messageReceivedCallback)
 {
     ReceiveInternal(new ReceiveState(sourceSocket, SocketUtils.MessageHeaderLength, messageReceivedCallback));
 }
Esempio n. 9
0
        private void StartToReceiveMessageBody(ReceiveState receiveState, byte[] messageHeaderBuffer, SocketInfo sourceSocketInfo, int bytesRead)
        {
            string errorMessage;
            var    messageLength = SocketUtils.ParseMessageLength(messageHeaderBuffer, out errorMessage);

            if (messageLength > 0)
            {
                receiveState.MessageSize = messageLength;
                _logger.DebugFormat("Start to receive new message, message body size:{0}, bytesRead:{1}", receiveState.MessageSize, bytesRead);
                var size = receiveState.MessageSize <= ReceiveState.BufferSize ? receiveState.MessageSize.Value : ReceiveState.BufferSize;
                receiveState.ReceivedData.Clear();
                receiveState.ClearBuffer();
                receiveState.ReceiveSize = size;
                ReceiveInternal(receiveState);
            }
            else
            {
                _logger.ErrorFormat("Parse message length failed, source socket address:{0}, receiveSize:{1}, bytesRead:{2}, errorMessage:{3}",
                                    sourceSocketInfo.SocketRemotingEndpointAddress, receiveState.ReceiveSize, bytesRead, errorMessage);
            }
        }
Esempio n. 10
0
 public SendContext(SocketInfo targetSocket, byte[] message, Action <SendResult> messageSendCallback)
 {
     TargetSocket        = targetSocket;
     Message             = message;
     MessageSendCallback = messageSendCallback;
 }