c# TCP服务器无法响应客户端
本文关键字:响应 客户端 TCP 服务器 | 更新日期: 2023-09-27 17:53:21
所以我现在的工作是创建一个服务器,可以响应并连接到几个客户端一次,这就是为什么我创建一个线程服务器和一些测试客户端检查。
客户端可以通过按下一个按钮连接到服务器,它将发送一个消息给服务器,服务器将该消息发送到其接口,然后响应客户端。最后,客户机将接收响应并将其放入其接口。
我现在得到的问题是服务器可以从服务器接收消息并显示,但从服务器到客户端的响应是不成功的,即使它们是相似的。从调试器来看,客户端似乎卡在读取过程中了。
下面是服务器的代码。我认为问题出现在连接处理程序和客户端。我现在卡住了,请告诉我我做错了什么@@
public class Server
{
TcpListener serverSocket = new TcpListener(IPAddress.Any, 3000);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
private exampleCallback callback;
public Server(exampleCallback Callback)
{
callback = Callback;
}
public void initServer()
{
serverSocket.Start();
//Call back to main thread to update display
if (callback != null)
callback(">> Server Initialized!");
Console.WriteLine(">> Server Initialized!");
}
public void waitConnection()
{
int counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
if (callback != null)
callback(">> Client number: " + counter + " started!");
Console.WriteLine(">> Client number: " + counter + " started!");
handleClient handerler = new handleClient(new exampleCallback(receiveCallback), clientSocket, counter);
Thread clientThread = new Thread(new ThreadStart(handerler.startConv));
clientThread.Start();
}
}
public void closeServer()
{
clientSocket.Close();
serverSocket.Stop();
}
private void receiveCallback(string message)
{
callback(message);
}
}
连接处理程序代码:
public class handleClient
{
private exampleCallback callback2;
TcpClient clientSocket;
int clientNo;
public handleClient(exampleCallback Callback, TcpClient client, int clNo)
{
callback2 = Callback;
clientSocket = client;
clientNo = clNo;
}
public void startConv()
{
int requestCount = 0;
byte[] byteFrom = new byte[10025];
string XMLfromClient = null;
string dataFromClient = null;
string serverResponse = null;
string serverXMLResponse = null;
NetworkStream serverStream = clientSocket.GetStream();
requestCount = 0;
while (true)
{
try
{
requestCount++;
//Receive requerst from client
serverStream.Read(byteFrom, 0, (int)clientSocket.ReceiveBufferSize);
XMLfromClient = System.Text.Encoding.ASCII.GetString(byteFrom);
callback2("'n >> From Client :" + clientNo + ". Message: 'n" + XMLfromClient);
//Console.WriteLine(">> From Client :" + clientNo + ". Message: 'n" + XMLfromClient);
//Send acknowledgement to client
serverResponse = "Server to Client(" + clientNo + "). Request time: " + requestCount;
byte[] byteTo = Encoding.ASCII.GetBytes(serverResponse);
serverStream.Write(byteTo, 0, byteTo.Length);
serverStream.Flush();
Console.WriteLine(">> " + serverResponse);
}
catch (Exception ex)
{
callback2(ex.ToString());
}
}
}
}
最后是客户端大小的代码:
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream;
public Form1()
{
InitializeComponent();
}
public void msg(string mesg)
{
this.Display.Text += Environment.NewLine + " >> " + mesg;
}
private void SendButton_Click(object sender, EventArgs e)
{
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("World Domination");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread receive = new Thread(new ThreadStart(ReceiveMess));
}
private void ReceiveMess()
{
serverStream = clientSocket.GetStream();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
msg("Data from Server : " + returndata);
}
private void connectButton_Click(object sender, EventArgs e)
{
msg("Client Started");
clientSocket.Connect("127.0.0.1", 3000);
this.Display.Text = "Client Socket Program - Server Connected ...";
}
}
您似乎忘记启动receive
线程:
private void SendButton_Click(object sender, EventArgs e)
{
// ... skipped .........
Thread receive = new Thread(new ThreadStart(ReceiveMess));
receive.Start(); // <--- try adding this line
}
服务器将消息发送到其接口,然后响应客户端
所以服务器是一个GUI应用程序?
基于代码,你似乎有阻塞操作(例如:AcceptTcpClient
)在GUI线程上。这是要失败的。GUI线程将阻塞(UI将无响应),这意味着工作线程对IO的更新将阻塞等待UI(所有UI操作必须发生在主线程上)。
另外,为每个连接旋转一个新线程是一个坏主意。线程开销很大。
你需要从头开始重写(客户端和服务器)。
- 避免在GUI线程上阻塞操作(即使是文件IO,如果你想要最大的性能)/
- 所有的socket操作都应该在线程池中运行(让系统为你管理线程)。
- 避免后台线程等待GUI (
BeginInvoke
优于Invoke
)。
使用async
更好:系统将为您管理线程切换。