[英]Winforms server socket application
我正在尝试创建一个Winforms应用程序,该应用程序侦听端口10000上的流量,并且基本上充当客户端应用程序和远程数据库的中间人。 它应该具有一个侦听和接受线程,当客户端连接时,该线程将打开一个单独的客户端线程。 然后,该客户端线程将处理与客户端程序的通信。 侦听器应用程序具有两个列表框,其中包含有关正在连接的用户和正在执行的操作的信息。
目前,我正在尝试使用Microsoft在此处提供的示例程序并根据我的需要对其进行修改,但是如果有人对我可能会看到的其他地方有任何建议,我将很乐意听到。
当我尝试解决这个问题时,我还无法弄清的一件事是如何在不锁定计算机的情况下使该侦听器继续运行。 这是我的表单代码(包括退出按钮和清除我的列表框的按钮):
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.