Reputation: 2523
I have a small Windows Form that when I press a press a button a socket goes into a listen state. I'm sending it data from a client program (just simple text) and my Form displays the information.
I want the program to continue listening for more data until I press a "cancel" button or something.
When I press the listen button again I get an error when I try to bind() the socket.
An invalid argument was supplied
This error only pops up the second time I'm pressing the button. I've tried closing the socket once information is received. And setting the LingerOption to false.
The code that's called when I push the listen button is
s1.Bind(endP);
s1.Listen(10);
connected = true;
Receive();
s1.Shutdown(SocketShutdown.Both);
s1.Close();
Anybody have an idea of what I'm missing?
Thanks a lot.
Upvotes: 0
Views: 2442
Reputation: 1
TcpClient tcpClient = new TcpClient(_ipAddress, _port) { ReceiveTimeout = 10 };
NetworkStream networkStream = tcpClient.GetStream();
networkStream.Write(bytesToSend1, 0, bytesToSend1.Length);
byte[] tmpBytesRead = new byte[1024];
Thread.Sleep(150);
int totalBytesRead = networkStream.Read(tmpBytesRead, 0, tmpBytesRead.Length);
networkStream.Close();
tcpClient.Close();
Upvotes: 0
Reputation: 25601
I think you may misunderstand the meaning of Listen. Listen is not to begin receiving input, but rather to start checking for new connections. Your statement about "listening for more data" suggests you belive that listen is for receiving data, not connections. "Receive" and "Available" are for checking on and receiving more data. Listen is for marking the socket as one that receives new connections, and Accept is to begin receiving from a new connection.
Upvotes: 1
Reputation: 13897
You can only bind a single socket to a port using regular socket APIs. You should have a single listening socket which accepts new sockets (And remains listening for new sockets after accepting). You don't receive/send on this listener.
s1.Bind(endP);
s1.Listen(10);
while (true) {
Socket s2 = s1.Accept();
s2.Receive();
s2.Close();
}
Upvotes: 2