Glossary Item Box
As the topic Creating A Simple Echo Server demonstrates, it is quite easy to create a server application using the Server component. With a few modifications to the echo server, you can create a server application which responds to commands. This is useful if you are implementing a protocol.
This walk-through won't attempt to demonstrate implementing an actual protocol, but instead it demonstrates a server that has three conditions:
To create a server which handles commands
[Visual Basic, C#]
[C#] // Begin listening on port 8888 server1.Listen(8888); [Visual Basic] ' Begin listening on port 8888 Server1.Listen(8888)
[Visual Basic, C#]
[C#] private void server1_Connection(object sender, Dart.PowerTCP.SslSockets.ConnectionEventArgs e) { // The Tcp instance used to communicate with the client is // found in e.Tcp. try { while(e.Tcp.Connected) { // Receive data until a CRLF is found or 1024 bytes are read using the stream-interface. bool found = false; string s = e.Tcp.Stream.Read("\r\n", 1024, ref found); // Trim any whitespace s = s.Trim(); // Take action on the command switch(s.ToUpper()) { case "COUNT": // Send connection count e.Tcp.Stream.Write("Current connection(s): " + server1.Connections.Count + "\r\n"); break; case "QUIT": // Send goodbye greeting and disconnect e.Tcp.Stream.Write("Goodbye\r\n"); e.Tcp.Close(); break; default: // Send error message e.Tcp.Stream.Write("Command " + s + " not understood.\r\n"); break; } } } catch(Exception ex) { // Just eat the exception } } [Visual Basic] Private Sub Server1_Connection(ByVal sender As Object, ByVal e As Dart.PowerTCP.SslSockets.ConnectionEventArgs) Handles Server1.Connection ' The Tcp instance used to communicate with the client is ' found in e.Tcp. Try Do While (e.Tcp.Connected) ' Receive data until a CRLF is found or 1024 bytes are read using the stream-interface. Dim found As Boolean = False Dim s As String = e.Tcp.Stream.Read(vbCrLf, 1024, found) ' Trim any whitespace s = s.Trim() ' Take action on the command Select Case (s.ToUpper()) Case "COUNT" ' Send connection count e.Tcp.Stream.Write("Current connection(s): " + Server1.Connections.Count.ToString() + vbCrLf) Case "QUIT" ' Send goodbye greeting and disconnect e.Tcp.Stream.Write("Goodbye" + vbCrLf) e.Tcp.Close() Case Else ' Send error message e.Tcp.Stream.Write("Command " + s + " not understood." + vbCrLf) End Select Loop Catch ex As Exception ' Just eat the exception End Try End Sub
Send comments on this topic.
Documentation version 1.1.2.0.
© 2008 Dart Communications. All rights reserved.