views:

343

answers:

3

Why won't the following code work in C#?

var c1 = new TcpClient(new IPEndPoint(IPAddress.Any, 8787));
var c2 = new TcpClient(new IPEndPoint(IPAddress.Any, 8788));
c1.Connect("localhost", 8788);

I get a "connection cannot be made because the target machine actively refused it". So, the TcpClient constructor doesn't appear to be binding the port, but I tried the Socket.Bind() function with no luck either.

A: 

The problem is that you're not listening for connections. You have to use a TcpListener or similar.

Mystere Man
+3  A: 

Two TcpClient's can't talk to each other. You need one TcpClient and one TcpListener.

Sam
TcpListener: http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx
Maxwell Troy Milton King
Is there any simpler way? I don't need to accept more than a single connection. Is a TcpClient simply not able to respond to a SYN?
Nayruden
@Nayruden, no, `TcpClient` can't accept a connection. To communicate you need a client and a server. Client connects to server. If you're really talking about always communicating on the same computer, inter-process-communication, then there are a bunch of options on how to do IPC, but TCP is still very common and one of the simplest methods.
Sam
A: 

I agree with Sam. You can find an example here.

Maurizio Reginelli