简体   繁体   English

C#套接字连接在下一个winform中丢失了

[英]C# Socket Connection lost in the next winform

I have a 'form1' and a 'form2'. 我有'form1'和'form2'。

Im currently using TCP IP socket on C#. 我目前在C#上使用TCP IP套接字。 After im connected to my server on form1, form2 is loaded. 在我连接到form1上的服务器后,加载了form2。 However, on form2, im not connect already and i received an error saying its not connect. 但是,在form2上,我还没有连接,我收到一个错误,说它没有连接。

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#. 它是一个简单的C#聊天应用程序,对于C#来说还是一个新手。

form1(below is my connect button codes) form1(下面是我的连接按钮代码)

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) 表单2(下面是我发送到服务器的消息按钮的代码)

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 IMO解决这个问题的方法是将所有套接字行为封装到一些提供行为的类中(而不是基于套接字的API),然后将对此实例的引用传递给您的表单,即

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: 显然,您的MainForm实例也可以向前传递:

void ShowChildForm() {
    var childForm = new ChildForm();
    childForm.Comms = Comms;
    childForm.Show();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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