[英]tcplistener and client in same Forms app
我有這段代碼似乎無法在Socket client = listener.AcceptSocket();
此代碼在控制台應用程序中工作正常,但是當我嘗試在Windows窗體應用程序中使用它時,它無法啟動/ Windows無法顯示
這是我的代碼:
public Form1()
{
InitializeComponent();
Listen();
}
public void Listen()
{
try
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
Console.WriteLine("Starting TCP listener...");
TcpListener listener = new TcpListener(ipAddress, 1302);
listener.Start();
while (true)
{
Console.WriteLine("Server is listening on " + listener.LocalEndpoint);
Console.WriteLine("Waiting for a connection...");
Socket client = listener.AcceptSocket(); // <----- PROBLEM
Console.WriteLine("Connection accepted.");
Console.WriteLine("Reading data...");
byte[] data = new byte[100];
int size = client.Receive(data);
Console.WriteLine("Recieved data: ");
for (int i = 0; i < size; i++)
Console.Write(Convert.ToChar(data[i]));
Console.WriteLine();
client.Close();
}
listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.StackTrace);
Console.ReadLine();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != "")
{
textToSend = richTextBox1.Text;
run = true;
}
else
{
MessageBox.Show("Box Cant Be Empty");
run = false;
}
if (run)
{
try
{
TCPclient = new TcpClient(SERVER_IP, PORT_NO);
nwStream = TCPclient.GetStream();
}
catch
{
}
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
MessageBox.Show("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
}
}
即使正在運行的代碼繁忙,控制台也將繼續輸出。 它被繪制在您的應用程序之外。
您正在使用的Windows窗體需要主應用程序線程可用,以便其更新和繪制窗體。 您應該查找異步/等待模式,並學習將其用於阻止IO調用。 該主題太大,無法為您提供簡單的快速答案,但是您可以在此處找到有關異步/等待的一些信息: https ://msdn.microsoft.com/library/hh191443(vs.110) .aspx,盡管可能會更好一些googlefu可以找到的文章。
可以在此處找到有關UI響應性的一些其他信息: https : //msdn.microsoft.com/zh-cn/library/windows/desktop/dd744765(v=vs.85).aspx
Socket client = listener.AcceptSocket();
正在等待傳入的數據包。 除非並且直到它收到一個,WinForm UI才會顯示出來 ,因為您正在調用Listen();
在窗體構造函數中,從而阻塞了主線程(UI)。
運行Listen();
在單獨的線程中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.