Search code examples
c#socketstcptcpclienttcplistener

C# Using TcpListener on both Client and Server


I followed this tutorial to setup a client -> server TCP based windows forms application where the server receives a file from the client and it works well. The summary of the structure would be:

Server uses TcpListener to listen

Client uses TcpClient to send

Now I am trying to do the opposite by sending a file from the server to client, using the same method. I tried the following structure:

Server uses TcpClient to send

Client uses TcpListener to listen

However I get the following error:

Only one usage of each socket address (protocol/network address/port) is normally permitted

Is this because the client and the server is listening to the same port as described by the error? How else can I send and receive files both ways?

My code is the exact code posted in that thread I linked, therefore I didn't post it here. Let me know if I should post my code here as well :)


Solution

  • As others have commented, what you are trying to do is not a very good idea, but to answer your question:

    The error is pretty self-explanatory. You are trying to use a port number which is already in use. So, just use a different port number. (The PortN parameter in the tutorial.) In other words, have one pair of TcpListener and TcpClient communicate via port X, and the other (reverse) pair communicate via port X+1.