用户控件使用与主窗体相同的TCP连接
本文关键字:TCP 连接 窗体 控件 用户 | 更新日期: 2023-09-27 18:28:27
我有一个表单,它充当TCP客户端/服务器项目的客户端GUI。我有多个充当"页面"的用户控件,用户可以使用主GUI窗体上的按钮进行导航
我的问题是;这些用户控件中的每一个(以及主窗体)都需要能够与服务器通信(即向服务器发送消息)。
目前,为了实现这一点,我每次添加新的用户控件时都会打开一个新的连接,方法是将以下代码以及所有用户控件"页面"放在我的主表单中:
public partial class MainForm: Form
{
private IPEndPoint serverEndPoint;
private TcpClient myClient = new TcpClient();
public MainForm()
{
InitializeComponent();
serverEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), 8888);
myClient.Connect(serverEndPoint);
}
}
private void SendMessage(string msg)
{
NetworkStream clientStream = myClient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(msg);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
我希望能够做的是只在我的主窗体上有这些代码,并让添加到主窗体的每个用户控件使用已经打开的连接进行通信。我只是不确定我将如何做到这一点。
将连接封装在一个静态类中,并创建用于连接到服务器和发送消息的静态接口。你只需要在主窗体中打开一次连接。
static public class ServerCommunicator
{
static private IPEndPoint serverEndPoint;
static private TcpClient myClient = new TcpClient();
static public void Connect()
{
serverEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), 8888);
myClient.Connect(serverEndPoint);
}
static public void SendMessage(string msg)
{
NetworkStream clientStream = myClient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(msg);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
你的主要形式类变成:
public partial class MainForm: Form
{
public MainForm()
{
InitializeComponent();
ServerCommunicator.Connect();
// Sending a message:
ServerCommunicator.SendMessage("Hello server!");
}
}
ServerCommunicator.Connect()只需要在主窗体中调用一次。其他控件可以简单地调用SendMessage。