Reputation: 51
I have a 'form1' and a 'form2'.
Im currently using TCP IP socket on C#. After im connected to my server on form1, form2 is loaded. However, on form2, im not connect already and i received an error saying its not connect.
How do i ensure that its still connected on all the forms in my application? Im testing out on my pc right now. its a simple C# chat application and im pretty new to C#.
form1(below is my connect button codes)
clientSocket.Connect(tbxIP.Text, 8888);
serverStream = clientSocket.GetStream();
string faciName = "Facilitator:" + "$";
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(faciName);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
form 2( below are the codes for my send message button to the server)
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(tbxMessageBox.Text + "$");
if (serverStream != null)
{
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
tbxMessageBox.Clear();
}
Thank you.
Upvotes: 0
Views: 523
Reputation: 1062820
IMO the way to approach this is to encapsulate all the socket behaviour into some class that provides behaviour (instead of a socket based API), and then pass a reference to this instance to your forms, i.e.
ServerComms comms = new ServerComms(address);
comms.Open();
using(var mainForm = new MainForm()) {
mainForm.Comms = comms;
Application.Run(mainForm);
}
Obviously your MainForm
instance can also pass this onwards:
void ShowChildForm() {
var childForm = new ChildForm();
childForm.Comms = Comms;
childForm.Show();
}
Upvotes: 2