I have a C# server running under Ubuntu 12.04 using Mono, with the following code :
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...");
}
}
}
The server is able to receive the client requests, but is however unable to respond because it fails to connect everytime. Am I missing something in my code or is there something else at work here ?
The additional Socket Sender
you're declaring is unnecessary. The handlerSocket
you receive from listenerSocket.Accept()
is already the socket you can use to communicate with the client.
When you accept a connection using a server socket, what you get is a socket connected to the client. You don't have to create a new socket to connect (in fact, you can't). So, instead of creating and using Sender
, just use handlerSocket
:
handlerSocket.SendFile(_profileLocation);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.