c# - C# Windows 窗体应用程序在创建时冻结
问题描述
所以大约一周前,我开始在 C# 中测试 Sockets,我想制作一对一的聊天应用程序,如果通过 NetworkStream 发送消息,可以打开该应用程序,但是,我遇到了一个问题,一旦按钮是按下,表单启动,但它被冻结。
这是用于启动消息传递表单的代码
if(args[0] == "liveChat")
{
messagingforms msgfrms = new messagingforms(); // The actual messaging form
msgfrms.Show(); // Shows the messaging form but when it shows, it freezes
SendMessage("liveChat"); // This is a function I created to send a message through the NetworkStream
} // to start the messaging form for the client
当显示消息表单时,它会启动一个新线程,该线程要么开始侦听连接到服务器的客户端。这是客户端代码
// This is a snippet showing what happens when the form loaded
// There are variables such as ips to connect to, threads and NetworkStreams
private void messagingforms_Load(object sender, EventArgs e) // This is what happens when the messaging form loads
{
ConnectionListenerThread = new Thread(ConnectionListener);
ConnectionListenerThread.Start(); // Starts the function below
}
public static void ConnectionListener() // This is the code for the client which tries to connect to the server
{
tcpClient = new TcpClient();
tcpClient.Connect(connectTo, 4535);
dataStream = tcpClient.GetStream();
MessageRecieverThread = new Thread(messageListener);
MessageRecieverThread.Start(); // An infinite loop that sees if there are any incoming messages
SendMessage("Test message"); // I did this to test if the connection was successfull, and it is but the form
} // still wouldnt start responding
消息传递表单的服务器代码
private void messagingform_Load(object sender, EventArgs e)
{
startConnection = new Thread(awaitConnection);
startConnection.Start(); // Starts the thread that listens for connections; the function below.
}
public static void awaitConnection()
{
tcpListener = new TcpListener(IPAddress.Any, MessagingPort); // Starts to accept any incoming clients
tcpListener.Start(); // Starts the tcp listener
tcpClient = tcpListener.AcceptTcpClient(); // If there is an incoming client then it accepts it
dataStream = tcpClient.GetStream(); // Gets the networkStream
tcpListener.Stop(); // Stops listening for clients
startListeningForMessages = new Thread(messageListener); // Starts listening for any incoming messages
startListeningForMessages.Start(); // Starts the thread
}
堆栈溢出很新,所以如果格式需要修复,请告诉我。
解决方案
推荐阅读
- flutter - 坏状态:没有元素让电话号码列出
- javascript - 回调不是异步库中的函数
- visual-studio - 如何定位具有相同距离的对象
- ios - TableView Cell Swift 中的 CollectionView 混合卡片类型重用问题
- angularjs - 在 AngularJS 中找不到使用 CSS 选择器或 xPath 的元素
- sql - Postgres Select ILIKE %text% 在大字符串行上很慢
- mysql - 如何加入 2 个表但保留原始表中的所有值?
- r - 如何从列表 col 中的列表中提取最大值并将其添加为 tibble 中的新列?
- python - 从 Python 的 configparser 模块中的配置文件调用用户定义的函数
- linux - 为什么在docker中拉取图像时出现此错误