Connect client and server on same machine

Hi!

I’ve written a client and a server, both in separate Unity projects, and I’m trying to get them to connect through localhost (for development purposes). It works when I connect from different machines through my router, but not on one machine. I suspect this has to do because I then open two sockets on the same port on this machine.

How do I get my client and server to interact on the same machine? Thanks :slight_smile: Code below.

//SERVER
void Connect() 
{
    NetworkTransport.Init();

    int maxConnections = 10;
    int localPort = 8888;
    //int remotePort = 8888; //Server doesn't need remote port (right?).

    ConnectionConfig config = new ConnectionConfig();
    channelId = config.AddChannel(QosType.Reliable);

    HostTopology topology = new HostTopology(config, maxConnections);
    socketId = NetworkTransport.AddHost(topology, localPort);
}


//CLIENT (in another unity project)
void Connect()
{
    NetworkTransport.Init();

    int maxConnections = 10;
    //int localPort = 8889; I've tried assigning a different local port here (not sure if this even is the local port), but it doesn't work.
    int remotePort = 8888;

    ConnectionConfig config = new ConnectionConfig();
    channelId = config.AddChannel(QosType.Reliable);

    HostTopology topology = new HostTopology(config, maxConnections);
    socketId = NetworkTransport.AddHost(topology, remotePort); //Fails here (socketId = -1)

    byte error;
    connectionId = NetworkTransport.Connect(socketId, "localhost", remotePort, 0, out error);
}

Nevermind, I’ve fixed it. I don’t specify a port when creating a socket for the client (let OS choose it). Then I connect to my local IP adress instead of localhost. Works like a charm :slight_smile: