private void buttonSendComplexMessage_Click(object sender, EventArgs e) { try { // Create the message to send Messages.ComplexMessage message = new Messages.ComplexMessage(); message.UniqueID = Guid.NewGuid(); message.Time = DateTimeOffset.Now; message.Message = textBoxMessage.Text; // Serialize the message to a binary array byte[] binaryMessage = Messages.Util.Serialize(message); // Send the message; the state is used by ClientSocket_WriteCompleted to display an output to the log string description = "<complex message: " + message.UniqueID + ">"; SocketPacketProtocol.WritePacketAsync(ClientSocket, binaryMessage, description); textBoxLog.AppendText("Sending message " + description + Environment.NewLine); } catch (Exception ex) { ResetSocket(); textBoxLog.AppendText("Error sending message to socket: [" + ex.GetType().Name + "] " + ex.Message + Environment.NewLine); } finally { RefreshDisplay(); } }
/// <summary> /// Closes and clears the socket, without causing exceptions. /// </summary> private void ResetSocket() { // Close the socket ClientSocket.Close(); ClientSocket = null; ClientSocketReader = null; // Indicate there is no socket connection ClientSocketState = SocketState.Closed; }
private void buttonSendComplexMessage_Click(object sender, EventArgs e) { // This function sends a complex message to all connected clients Messages.ComplexMessage message = new Messages.ComplexMessage(); message.UniqueID = Guid.NewGuid(); message.Time = DateTimeOffset.Now; message.Message = textBoxMessage.Text; string description = "<complex message: " + message.UniqueID + ">"; // Serialize it to a binary array byte[] binaryObject = Messages.Util.Serialize(message); // Keep a list of all errors for child sockets Dictionary <ServerChildTcpSocket, Exception> SocketErrors = new Dictionary <ServerChildTcpSocket, Exception>(); // Start a send on each child socket foreach (KeyValuePair <ServerChildTcpSocket, ChildSocketContext> childSocket in ChildSockets) { // Ignore sockets that are disconnecting if (childSocket.Value.State != ChildSocketState.Connected) { continue; } try { textBoxLog.AppendText("Sending to " + childSocket.Key.RemoteEndPoint.ToString() + ": " + description + Environment.NewLine); SocketPacketProtocol.WritePacketAsync(childSocket.Key, binaryObject, description); } catch (Exception ex) { // Make a note of the error to handle later SocketErrors.Add(childSocket.Key, ex); } } // Handle all errors. This is done outside the enumeration loop because the child socket // error recovery will remove the socket from the list of child sockets. foreach (KeyValuePair <ServerChildTcpSocket, Exception> error in SocketErrors) { textBoxLog.AppendText("Child Socket error sending message to " + error.Key.RemoteEndPoint.ToString() + ": [" + error.Value.GetType().Name + "] " + error.Value.Message + Environment.NewLine); ResetChildSocket(error.Key); } // In case there were any errors, the display may need to be updated RefreshDisplay(); }
private void timer_Tick(object sender, EventArgs e) { try { // Every 5 seconds, this timer goes off, and we send a keepalive message if the socket is connected if (ClientSocketState == SocketState.Connected) { SocketPacketProtocol.WriteKeepaliveAsync(ClientSocket); } } catch (Exception ex) { ResetSocket(); textBoxLog.AppendText("Error sending keepalive to socket: [" + ex.GetType().Name + "] " + ex.Message + Environment.NewLine); } }
private void ListeningSocket_AcceptCompleted(AsyncResultEventArgs <ServerChildTcpSocket> e) { // Check for errors if (e.Error != null) { ResetListeningSocket(); textBoxLog.AppendText("Socket error during Accept: [" + e.Error.GetType().Name + "] " + e.Error.Message + Environment.NewLine); RefreshDisplay(); return; } // Always continue listening for other connections ListeningSocket.AcceptAsync(); ServerChildTcpSocket socket = e.Result; try { // Save the new child socket connection, and create a packetizer for it SocketPacketProtocol protocol = new SocketPacketProtocol(socket); ChildSocketContext context = new ChildSocketContext(); context.Protocol = protocol; context.State = ChildSocketState.Connected; ChildSockets.Add(socket, context); protocol.PacketArrived += (args) => ChildSocket_PacketArrived(socket, args); socket.WriteCompleted += (args) => ChildSocket_WriteCompleted(socket, args); socket.ShutdownCompleted += (args) => ChildSocket_ShutdownCompleted(socket, args); // Display the connection information textBoxLog.AppendText("Connection established to " + socket.RemoteEndPoint.ToString() + Environment.NewLine); // Start reading data from the connection protocol.Start(); } catch (Exception ex) { ResetChildSocket(socket); textBoxLog.AppendText("Socket error accepting connection: [" + ex.GetType().Name + "] " + ex.Message + Environment.NewLine); } finally { RefreshDisplay(); } }
private void buttonConnect_Click(object sender, EventArgs e) { try { // Read the IP address IPAddress serverIPAddress; if (!IPAddress.TryParse(textBoxIPAddress.Text, out serverIPAddress)) { MessageBox.Show("Invalid IP address: " + textBoxIPAddress.Text); textBoxIPAddress.Focus(); return; } // Read the port number int port; if (!int.TryParse(textBoxPort.Text, out port)) { MessageBox.Show("Invalid port number: " + textBoxPort.Text); textBoxPort.Focus(); return; } // Begin connecting to the remote IP ClientSocket = new ClientTcpSocket(); ClientSocketReader = new SocketPacketProtocol(ClientSocket); ClientSocket.ConnectCompleted += ClientSocket_ConnectCompleted; ClientSocket.WriteCompleted += ClientSocket_WriteCompleted; ClientSocket.ShutdownCompleted += ClientSocket_ShutdownCompleted; ClientSocketReader.PacketArrived += ClientSocket_PacketArrived; ClientSocket.ConnectAsync(serverIPAddress, port); ClientSocketState = SocketState.Connecting; textBoxLog.AppendText("Connecting socket to " + (new IPEndPoint(serverIPAddress, port)).ToString() + Environment.NewLine); } catch (Exception ex) { ResetSocket(); textBoxLog.AppendText("Error creating connecting socket: [" + ex.GetType().Name + "] " + ex.Message + Environment.NewLine); } finally { RefreshDisplay(); } }
private void timer_Tick(object sender, EventArgs e) { // Every 5 seconds, this timer goes off, and we send a keepalive message to all connected clients // Keep a list of all errors for child sockets Dictionary <ServerChildTcpSocket, Exception> SocketErrors = new Dictionary <ServerChildTcpSocket, Exception>(); // Send a keepalive to all clients foreach (KeyValuePair <ServerChildTcpSocket, ChildSocketContext> childSocket in ChildSockets) { try { if (childSocket.Value.State != ChildSocketState.Connected) { continue; } SocketPacketProtocol.WriteKeepaliveAsync(childSocket.Key); } catch (Exception ex) { // Make a note of the error to handle later SocketErrors.Add(childSocket.Key, ex); } } // Handle all errors. This is done outside the enumeration loop because the child socket // error recovery will remove the socket from the list of child sockets. foreach (KeyValuePair <ServerChildTcpSocket, Exception> error in SocketErrors) { textBoxLog.AppendText("Child Socket error sending keepalive to " + error.Key.RemoteEndPoint.ToString() + ": [" + error.Value.GetType().Name + "] " + error.Value.Message + Environment.NewLine); ResetChildSocket(error.Key); } // In case there were any errors, the display may need to be updated RefreshDisplay(); }