Florian Becker
Florian Becker

Reputation: 113

Local Inter-process Communication via TCP Sockets in C#

I get an exception when doing this in one thread:

var listener = new TcpListener(new IPEndPoint("127.0.0.1", 3536));
listener.Start();

System.Net.Sockets.SocketException (0x80004005): Address already in use

and this in another thread:

var client = new TcpClient(new IPEndPoint("127.0.0.1", 3536));

I know that I can't create two sockets on the same port, but I want one thing and the other receiving.

What I want to achieve is inter-process communication between a LOCAL C# and Python program. I've opted for sockets cause pipes work differently on Windows and Unix Systems and I wanted the possibility to outsource one program to another machine.

Edit: The TCP listener runs flawlessly when I remove

var client = new TcpClient(new IPEndPoint("127.0.0.1", 3536));

Edit2: I've had a

Thread.Sleep

on my main Thread. If I replace it with

while (!client.Connected) client.Connect(ipEndPoint)
Console.WriteLine(client.Connected) // this reaches

I don't currently know about data-transfer yet

Upvotes: 0

Views: 1456

Answers (1)

akop
akop

Reputation: 7891

You are using the wrong constructor.

TcpClient(IPEndPoint)
Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.

What you probably want is this:

TcpClient(String, Int32)
Initializes a new instance of the TcpClient class and connects to the specified port on the specified host.

See TcpClient constructors

Some knowledge: A client needs a free port too. Normally it will binds to a random free port. For a local connection are two sockets required - one for the client and one for the server.

Upvotes: 1

Related Questions