简体   繁体   中英

Client Server Socket C# communication

I have wrote a group chat using C#, using client socket and server socket. the communication between the client and the server works fine when I run the programs (both server and client) in my own pc using VS 2017. When I run the Client program in a laptop and the server in my own pc (still using VS 2017, although I don't think this is matter) the client doesn't connect to the server.

my question is how I connect the server and the client outside of the localhost?

I will add the functions from the server and client side the responsible for connecting each other.

function in the server code that start up the server:

public static void ServerUp()
{
    IPAddress ipAdd = IPAddress.Parse("127.0.0.1");
    TcpListener myListener = new TcpListener(ipAdd, 8001);
    myListener.Start();
    Console.WriteLine("The server running at port: " + myListener.LocalEndpoint);
    users = new List<ClientSocket>();
}

function in the client code that connect to server:

public static void ConnectToServer()
{
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    Console.WriteLine("Connecting...");
    IPEndPoint ipAdd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001);
    socket.Connect(ipAdd);
    Console.WriteLine("Connected");
    Console.WriteLine(new string('-',Console.WindowWidth));
}

If you run the client on another computer, it crosses the network.

Unless you opened a firewall port for your server somehow, the windows integrated firewall will block all access from outside sources.

Simple as that.

Go to the advanced firewall settings and open the port for the server.

Change the IPs. 127.0.0.1 is used for localhost. Use your local network IPs eg 192.168.1.10 etc etc. Also have the required port (8001) open on the firewall of the server machine.

You need the server to listen on the real ip address of your pc instead of 127.0.0.1, and also in the client, on your laptop, you have to use the ip address of your computer instead of 127.0.0.1.

127.0.0.1 is the local network address, which is not bound to your network connection and only reachable on the same computer, not on the network.

Further your windows firewall might block the incoming connection - either add a inbound tcp rule for port 8001 an your computer or temporarily disable the firewall on your computer.

127.0.0.1是本地IP,请使用网络的DHCP服务器分配的IP。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM