简体   繁体   中英

SocketServer and socket communication

I have a question about the SocketServer and Socket connection in java regarding when using a host other than localhost.

I am trying to write a simple chat program and I was hoping to make other people in my house connect to it. This is the code where I create my socketserver and socket:

Server part:

    try{
        ServerSocket socket=new ServerSocket(4444);
        while(true){
            Socket socket1=socket.accept();
            new ClientThread(socket1);
        }

Client part:

      socket=new Socket("localhost",4444);

To test my program, I am opening two command prompts on my computer, one for the server and one for the client. When I use localhost as the host everything works fine. Similarly, when I use the IPv4 address found under ipconfig it works fine too.

However, when I try using the address I get from whatsmyip as the host. eg:

      socket=new Socket("114.89.XX.XXX",4444);

I get no connection and finally a connection time out error.

So my question would be : how should I make it work with the 114.89.XX.XXX ip? Also, if I wanted to make other computers connect to this SocketServer, should other computers use the 114.89.XX.XXX ip when creating a socket too?

Too long for a comment

Your host is running on a local network that is isolated from the Internet by a router, most likely provided by your ISP. Your host's actual IP address is likely something like 192.168.xx which is a local private address and is not reachable from the Internet. Outgoing packets and incoming replies are subject to NAT (Network Address Translation).

whatismyip.com returns the IP address of your router's connection to the Internet, and your router's firewall blocks all incoming traffic. If you want this to work so that a host somewhere on the Internet could connect to your server you would need to open the port on the router's firewall and also configure the router to forward incoming traffic to your host. Probably also you'd need to configure the firewall on your host to allow incoming traffic from the router.

Explaining all this is off-topic for StackOverflow as it is a tutorial in basic networking; it probably belongs on ServerFault , but may be off-topic there as well, as "too broad".

Sounds like you need to study basic networking concepts including routing, IP address formats, firewalls, NAT and port forwarding.

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