I am looking for a way to implement a protocol in TCP for sending and receiving simple string messages. I have a client and a server app and when both start running for the first time I press the connect button on the client to connect to the server. Some text pops up on the server's listbox saying that a client has connected, and on the client's listbox some text appears saying that it is connected to the server.
That part works ok, but now I want to be able to send other strings to the server and depending on what string I send over would make the server perform a certain operation, how can I do this? First idea that comes to mind is to use if-then statements somewhere. I will post my code below:
Server:
private static int port = 8080;
private static TcpListener listener;
private static Thread thread;
private void Form1_Load(object sender, EventArgs e)
{
listener = new TcpListener(new IPAddress(new byte[] { 10, 1, 6, 130 }), port);
thread = new Thread(new ThreadStart(Listen));
thread.Start();
}
private void Listen()
{
listener.Start();
listBox1.Invoke(new EventHandler(delegate { listBox1.Items.Add("Listening on: " + port.ToString()); }));
while (true)
{
listBox1.Invoke(new EventHandler(delegate { listBox1.Items.Add("Waiting for connection...."); }));
TcpClient client = listener.AcceptTcpClient();
Thread listenThread = new Thread(new ParameterizedThreadStart(ListenThread));
listenThread.Start(client);
}
}
//client thread
private void ListenThread(Object client)
{
NetworkStream netstream = ((TcpClient)client).GetStream();
listBox1.Invoke(new EventHandler(delegate { listBox1.Items.Add("Request made"); }));
byte[] resMessage = Encoding.ASCII.GetBytes("Connected to Server");
netstream.Write(resMessage, 0, resMessage.Length);
netstream.Flush();
}
Client:
TcpClient tcpclnt;
private void buttonConnect_Click(object sender, EventArgs e)
{
try
{
tcpclnt = new TcpClient();
userEventBox.Items.Add("Connecting.....");
try
{
tcpclnt.Connect("10.1.6.130", 8080);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
Stream stm = tcpclnt.GetStream();
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string returndata = System.Text.Encoding.ASCII.GetString(bb);
userEventBox.Items.Add(returndata);
tabControl1.Enabled = true;
//need a way for the server see this string
string populateList = "Test";
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(populateList);
stm.Write(ba, 0, ba.Length);
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
}
I am quite stuck and would appreciate any help you could provide on this subject. Thank you.
Source -> C# client-server protocol/model question