Pareidolia
Pareidolia

Reputation: 309

TCP Socket send/receive always waiting

I have a TCP connection between a server and a client. Server sending data, client receiving data and client feedback the server. But if client closes socket and creates again, server never accept it because it is waiting feedback from client. So how can i solve that?

Server

byte[] buffer = new byte[1000];
string ip = "192.168.1.17";
int port = 15500;

IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint localEndpoint = new IPEndPoint(ipAddress, port);

Socket sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

Console.WriteLine("Waiting client...");
sock.Bind(localEndpoint);
sock.Listen(5);

Socket confd = sock.Accept();

Console.WriteLine("Connected with {0} at port {1}", ip, port);
Sender sender = new Sender();
Receiver receiver = new Receiver();

while (true) {
    if (confd.Connected) {
        sender.SendData(confd);
        receiver.ReceiveData(confd); //Waiting here
    } 
    else {
        confd.Close();
        Console.WriteLine("Waiting client...");
        confd = sock.Accept();
    }
}

Upvotes: 1

Views: 3072

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063884

Having a thread per socket is usually a bad idea. Having a single thread that deals with socket IO and accepting connections is usually a terrible idea. There are a myriad reasons why a socket disconnect can go unnoticed - either for a while, or in some cases: indefinitely. The way to avoid this problem is usually to have one thread (or theses days: async loop) dedicated to accepting connections, and initializing connections, and then rather than creating a thread per socket, use async IO to read/write without requiring threads. Although if you have a very low number of sockets, you might be able to get away with thread-per-socket. Finally, either use read/write timeouts, or have a periodic "have I seen this socket lately?" check (over all sockets), to help shut down sockets that have failed silently.

Upvotes: 3

Related Questions