我用 C# winforms 编写了这段代码,但它在第 33 行崩溃,并且会被冻结并且没有响应。 我将所有代码放在按钮单击中,以便当我单击按钮时服务器运行并且客户端可以连接到该按钮。 如果您用您的解决方案解决这个问题,我会很高兴。
using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace Server_SP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Socket listenerr = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress localAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndpoint = new IPEndPoint(localAddress, 8575);
listenerr.Bind(localEndpoint);
IPAddress ipAddress = IPAddress.Parse("0.0.0.0");
int port = 8575;
TcpListener listener = new TcpListener(ipAddress, port);
listener.Start();
label2.Text = "Serving on Port 8587";
while (true)
{
label1.Text = " Waiting for connection...";
TcpClient cliend = listener.AcceptTcpClient();
label1.Text = "Client Accepted";
NetworkStream stream = cliend.GetStream();
StreamReader sr = new StreamReader(cliend.GetStream());
StreamWriter sw = new StreamWriter(cliend.GetStream());
try
{
byte[] buffer = new byte[1024];
stream.Read(buffer, 0, buffer.Length);
int count = 0;
//////how many bytes
foreach (byte b in buffer)
{
if (b!=0)
{
count++;
}
}
string reced = Encoding.UTF8.GetString(buffer, 0, count);
label3.Text = "Request Reced: " + reced;
sw.WriteLine("Hiiii.I am serverrr");
sw.Flush();
}
catch (Exception errorr)
{
label1.Text = "Errorrrr";
sw.WriteLine(errorr.ToString());
}
}
}
}
}
我删除了 while 循环,并用下面的代码替换了第 41 行,但没有帮助。
TcpClient cliend = listenerr.AcceptTcpClient();
实际上,我在控制台中正确完成了这项工作并且可以正常工作,但是当我尝试将该代码移植到 Windows 应用程序时,我遇到了这些问题。
看来你需要将服务器代码移至单独的线程以避免像这样阻塞UI
private void button1_Click(object sender, EventArgs e)
{
await Task.Run(()=>HandleServer());
}
private void HandleServer()
{
// do your stuff run the server and also the while loop
}