Socket Connections
-
Dear all, I'm trying to get my computer to listen on a port and pass on the received data ( after some modification ) over Multicast. I'm receiving data on the socket every second. I wrote the code below and it works perfect. The problem that I require some assistance with is pretty simply. Everytime a string of data is received, the socket is closed and new socket is opened to wait for the next string. When the next string of data comes in, it gets processed and the socket is closed again. This means that after a period of time, lots of socket connections are made. One of them is active and the others are in a TIME_WAIT state ( and that list keeps growing ) Is there a way around this ?
Int32 port = 31008;
IPAddress localAddr = IPAddress.Any; server = new TcpListener(localAddr, port); server.Start(); // Buffer for reading data Byte\[\] bytes = new Byte\[256\]; String data = null; while (true) { client = server.AcceptTcpClient(); data = null; NetworkStream stream = client.GetStream(); int i; while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); data = data.ToUpper(); byte\[\] msg = System.Text.Encoding.ASCII.GetBytes(data); SendMulticast(MultiCastIP, MultiCastPort, msg); } client.Close(); }
kind regards, Rick
-
Dear all, I'm trying to get my computer to listen on a port and pass on the received data ( after some modification ) over Multicast. I'm receiving data on the socket every second. I wrote the code below and it works perfect. The problem that I require some assistance with is pretty simply. Everytime a string of data is received, the socket is closed and new socket is opened to wait for the next string. When the next string of data comes in, it gets processed and the socket is closed again. This means that after a period of time, lots of socket connections are made. One of them is active and the others are in a TIME_WAIT state ( and that list keeps growing ) Is there a way around this ?
Int32 port = 31008;
IPAddress localAddr = IPAddress.Any; server = new TcpListener(localAddr, port); server.Start(); // Buffer for reading data Byte\[\] bytes = new Byte\[256\]; String data = null; while (true) { client = server.AcceptTcpClient(); data = null; NetworkStream stream = client.GetStream(); int i; while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); data = data.ToUpper(); byte\[\] msg = System.Text.Encoding.ASCII.GetBytes(data); SendMulticast(MultiCastIP, MultiCastPort, msg); } client.Close(); }
kind regards, Rick
The TIME_WAIT state for a period of time is normal/default socket behavior. If you're absolutely sure all data is sent, then you may be able to set the LingerState to on/0sec:
LingerOption lingerOption = new LingerOption (true, 0);
client.LingerState = lingerOption;You also should call Close() on your NetworkStream :) Mark
Mark Salsbery Microsoft MVP - Visual C++ :java: