我正在尝试创建一个 winforms 应用程序,该应用程序监听端口 10000 上的流量,并且基本上充当客户端应用程序和远程数据库的中间人。它应该有一个监听和接受线程,当客户端连接时,它会打开一个单独的客户端线程。然后,该客户端线程将处理与客户端程序的通信。监听器应用程序有两个列表框,其中包含有关正在连接的用户和正在执行的操作的信息。
现在,我正在尝试使用 Microsoft 提供的示例程序 here并根据我的需要修改它,但如果有人对我可能在哪里查看有任何建议,我很乐意听到。
当我试图解决这个问题时,我还没能弄清楚的一件事是如何在不锁定我的计算机的情况下让这个监听器继续工作。这是我的表单代码(包括退出按钮和清除列表框的按钮):
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e) {
this.Close();
}
private void btnClearList_Click(object sender, EventArgs e) {
this.lbActionLog.Items.Clear();
this.lbUserLog.Items.Clear();
count = 0;
this.txtCount.Text = count.ToString();
}
private void Form1_Load(object sender, EventArgs e) {
Server begin = new Server();
begin.createListener();
}
}
这是我的监听器代码,使用 begin.createListener 调用:
int servPort = 10000;
public void createListener() {
// Create an instance of the TcpListener class.
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
string output = "";
try {
// Set the listener on the local IP address and specify the port.
//
tcpListener = new TcpListener(ipAddress, servPort);
tcpListener.Start();
output = "Waiting for a connection...";
}
catch (Exception e) {
output = "Error: " + e.ToString();
MessageBox.Show(output);
}
while (true) {
// Always use a Sleep call in a while(true) loop
// to avoid locking up your CPU.
Thread.Sleep(10);
// Create socket
//Socket socket = tcpListener.AcceptSocket();
TcpClient tcpClient = tcpListener.AcceptTcpClient();
// Read the data stream from the client.
byte[] bytes = new byte[256];
NetworkStream stream = tcpClient.GetStream();
stream.Read(bytes, 0, bytes.Length);
SocketHelper helper = new SocketHelper();
helper.processMsg(tcpClient, stream, bytes);
}
}
现在,这只是在 tcpListener.AcceptSocket 上停止。该表单永远不会加载,并且显然列表框没有被填充。如何让这个监听器在应用程序启动时自动运行,并且仍然加载表单并更新列表框?我希望这个应用程序能够启动并随时准备好接受连接,而不需要已经有一个应用程序坐在那里等待。
最佳答案
您正在使用阻塞方法,以便 Form1_Load
永远不会结束,因为它等待传入连接。
一个简单的解决方法可能是启动一个处理连接的新线程:
private void Form1_Load(object sender, EventArgs e) {
new Thread(
() =>
{
Server begin = new Server();
begin.createListener();
}
).Start();
}
关于c# - Winforms 服务器套接字应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24567667/