简体   繁体   中英

C# Socket Connection lost in the next winform

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.

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, ie

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM