When working with TCP client sockets I often find myself frustrated with the lack of event-driven support. I usually end up writing a whole bunch of code to determine disconnects, reconnecting, etc and I figuired it's time to just write my own class for this stuff. I figuired I'd share it with all of you. The implementation is quite simple, I'll provide an example below. I have XML commented all the public properties and methods, the rest is up to you to figuire out if you want to make any changes!
public partial class Form1 : Form
{
EventDrivenTCPClient client;
public Form1()
{
InitializeComponent();
//Initialize the event driven client
client = new EventDrivenTCPClient(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));
//Initialize the events
client.DataReceived += new EventDrivenTCPClient.delDataReceived(client_DataReceived);
client.ConnectionStatusChanged += new EventDrivenTCPClient.delConnectionStatusChanged(client_ConnectionStatusChanged);
}
//Fired when the connection status changes in the TCP client - parsing these messages is up to the developer
//I'm just adding the .ToString() of the state enum to a richtextbox here
void client_ConnectionStatusChanged(EventDrivenTCPClient sender, EventDrivenTCPClient.ConnectionStatus status)
{
//Check if this event was fired on a different thread, if it is then we must invoke it on the UI thread
if (InvokeRequired)
{
Invoke(new EventDrivenTCPClient.delConnectionStatusChanged(client_ConnectionStatusChanged), sender, status);
return;
}
richTextBox1.Text += "Connection: " + status.ToString() + Environment.NewLine;
}
//Fired when new data is received in the TCP client
void client_DataReceived(EventDrivenTCPClient sender, object data)
{
//Again, check if this needs to be invoked in the UI thread
if (InvokeRequired)
{
try
{
Invoke(new EventDrivenTCPClient.delDataReceived(client_DataReceived),sender, data);
}
catch
{ }
return;
}
//Interpret the received data object as a string
string strData = data as string;
//Add the received data to a rich text box
richTextBox1.Text += strData + Environment.NewLine;
}
//Button1 is a "Connect" button
private void button1_Click(object sender, EventArgs e)
{
client.Connect();
}
//Button 2 is a 'Send Data' button
private void button2_Click(object sender, EventArgs e)
{
client.Send("Hello!");
}
}
This example requires a connect button called button1, a send data button called button2, a textbox for the IP address, a textbox for the port, and a richtextbox to display output. You will also (obviously) need a server to connect to that will send us data.