/// <summary> /// Executed when a message is accepted /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void _onReceived(object sender, SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { Debug.WriteLine("PersistantSocketController : Message reception successful"); string wholeMessage = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred); var messages = wholeMessage.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); if (MessageReceived != null) _uiThreadDispatcher.BeginInvoke(() => { foreach (var message in messages) MessageReceived(this, new MessageReceivedEventArgs { Message = message }); }); ReceiveLoop(); } else { Debug.WriteLine("PersistantSocketController : Message reception failed : {0}", e.SocketError); State = PersistantSocketState.Disconnected; } }
/// <summary> /// Executed on Ping End /// </summary> void _onPing(object sender, SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { Debug.WriteLine("PersistantSocketContoller : Ping SuccessFull"); // pong ! } else { Debug.WriteLine("PersistantSocketContoller : Ping failed ! : {0}", e.SocketError); //Error State = PersistantSocketState.Disconnected; } }
/// <summary> /// Exucuted on Connection end /// </summary> void _onConnected(object sender, SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { Debug.WriteLine("PersistantSocketContoller : Connection successful"); State = PersistantSocketState.Connected; ReceiveLoop(); } else { Debug.WriteLine("PersistantSocketContoller : Connexion failed : {0}", e.SocketError); State = PersistantSocketState.Disconnected; } }
/// <summary> /// Connect or Ping the server /// </summary> void BeginConnect(object notUsed) { Debug.WriteLine("PersistantSocketController.BeginConnect [State : {0}]", State); if (State == PersistantSocketState.Disconnected) { if(_realSocket != null) _realSocket.Dispose(); _realSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connection... var sockArgs = new SocketAsyncEventArgs { RemoteEndPoint = _endPoint }; State = PersistantSocketState.Connecting; sockArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_onConnected); if (!_realSocket.ConnectAsync(sockArgs)) _onConnected(_realSocket, sockArgs); } else if (State == PersistantSocketState.Connected) { // ping? byte[] buffer = System.Text.Encoding.UTF8.GetBytes("Ping?\r\n"); var sockArgs = new SocketAsyncEventArgs(); sockArgs.SetBuffer(buffer, 0, buffer.Length); sockArgs.RemoteEndPoint = _endPoint; sockArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_onPing); if (!_realSocket.SendAsync(sockArgs)) _onPing(_realSocket, sockArgs); } }
protected virtual void Dispose(bool disposing) { if (_disposed) return; _disposed = true; if (disposing) { if (_pingTimer != null) { _pingTimer.Dispose(); _pingTimer = null; } if (_realSocket != null) { _realSocket.Dispose(); _realSocket = null; } State = PersistantSocketState.Disconnected; } }
/// <summary> /// Send a message to the server synchronously /// </summary> /// <param name="message">Message to send</param> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="System.Net.Sockets.SocketException"></exception> public void SendMessage(string message) { if (State != PersistantSocketState.Connected) { throw new InvalidOperationException("The socket server is unavailable"); } bool success = false; using (AutoResetEvent are = new AutoResetEvent(false)) { EventHandler<SocketAsyncEventArgs> sendMessageCallback = delegate(object sender, SocketAsyncEventArgs asyncArgs) { if (asyncArgs.SocketError == SocketError.Success) success = true; are.Set(); }; if (!message.EndsWith("\r\n")) message += "\r\n"; var buffer = Encoding.UTF8.GetBytes(message); var toSend = new SocketAsyncEventArgs(); toSend.SetBuffer(buffer, 0, buffer.Length); toSend.RemoteEndPoint = _endPoint; toSend.Completed += sendMessageCallback; if (!_realSocket.SendAsync(toSend)) sendMessageCallback(_realSocket, toSend); else are.WaitOne(); if (!success) { State = PersistantSocketState.Disconnected; throw new System.Net.Sockets.SocketException((int)toSend.SocketError); } } }