c#TCP套接字服务器未响应客户端
本文关键字:响应 客户端 服务器 套接字 c#TCP | 更新日期: 2023-09-27 18:29:58
我有一个使用Mono在Ubuntu 12.04下运行的C#服务器,代码如下:
while (true)
{
Console.WriteLine("Socket ready...");
using (Socket handlerSocket = listenerSocket.Accept())
{
Console.WriteLine("New request...");
BackgroundWorker newBackgroundWorker = new BackgroundWorker();
byte[] buffer = new byte[1024];
Console.WriteLine("Buffer allocated...");
handlerSocket.Receive(buffer);
//newBackgroundWorker.DoWork += (s, o) =>
//{
using (Socket Sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Console.WriteLine("Buffer received...");
string request = Encoding.Unicode.GetString(buffer);
Console.WriteLine("New request from : {0} /t Request : {1}", ((IPEndPoint)handlerSocket.RemoteEndPoint).Address.ToString(), request);
if (request.Contains("$GetBattleList"))
{
//Chain of if's and else's continues
//The following else if is the only case being tested
else if (request.Contains("$GetZeroBasedProfile"))
{
Console.WriteLine("Sending profile...");
Sender.Connect(handlerSocket.RemoteEndPoint); //Fails here due to not being able to reach the client application, throws a timeout exception
Sender.SendFile(_profileLocation);
}
else Console.WriteLine("Invalid request. Ignoring...");
}
}
}
服务器能够接收客户端请求,但由于每次都无法连接,因此无法响应。我是在代码中遗漏了什么,还是这里有其他东西在起作用?
您所声明的附加Socket Sender
是不必要的。从listenerSocket.Accept()
收到的handlerSocket
已经是可以用于与客户端通信的套接字。
当您接受使用服务器套接字的连接时,您得到的是连接到客户端的套接字。你不必创建一个新的套接字来连接(事实上,你不能)。因此,与其创建和使用Sender
,不如使用handlerSocket
:
handlerSocket.SendFile(_profileLocation);