Windows Forms TCP Code Example
The following example demonstrates a simple TCP session in a Windows Forms environment. The client sends data to an echo server and receives it back. The session is executed asynchronously, without blocking the UI.
private void buttonStart_Click(object sender, EventArgs e)
//This application has a User-Interface, which we do not want to block.
//Start launches the specified method on a worker thread.
//Event handlers execute on the UI thread.
private void connect(object host)
//This function connects to an echo server and receives echoed data.
//The Start method is used to execute this function on a worker thread.
tcp1.Connect(new TcpSession(new Dart.Sockets.IPEndPoint(host.ToString(), 7)));
//Marshals data to the UI as it is received.
byte buffer = new byte;
while (tcp1.State == Dart.Sockets.ConnectionState.Connected)
tcp1.Marshal(tcp1.Read(buffer), "", null);
private void textInterface_KeyPress(object sender, KeyPressEventArgs e)
//The last line entered in the textbox is sent to the server.
//The app closes down when 'exit' is entered.
if (e.KeyChar == 13)
string lastLine = textInterface.Lines[textInterface.Lines.Count() - 1];
if (lastLine.ToLower() == "exit") tcp1.Close();
void tcp1_Data(object sender, Dart.Sockets.DataEventArgs e)
//This event is raised on the UI when data is marshaled from a worker thread.
//Displays the received data in the textbox.
if (e.Data != null)
textInterface.AppendText("> " + e.Data.ToString() + Environment.NewLine);
private void tcp1_StateChanged(object sender, EventArgs e)
//This event is raised when the Tcp component changes state.
textInterface.Enabled = (tcp1.State == Dart.Sockets.ConnectionState.Connected);
if (tcp1.State == Dart.Sockets.ConnectionState.Connected)