首页 > 解决方案 > 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
}

堆栈溢出很新,所以如果格式需要修复,请告诉我。

标签: c#socketssystem.net.sockets

解决方案


推荐阅读