简体   繁体   中英

Java Networking - Connecting two computers

I'm trying to write a simply program client-server program that would connect a Client machine to a Server machine.

My code so far works well on the localhost, but when I replace the ip address in the Client code to the local ip address of the Server machine no connection is done. I think my understanding of InetAddress is off.

Socket connect code: Client.java

InetAddress ip = InetAddress.getByName("my_ip_address");
Socket s = new Socket(ip, 9876); //<- where the connection timeout happens

You don't call getBytes() from a String to get your ip address like that; option 1: call getByName(String) like

InetAddress ip = InetAddress.getByName("127.0.0.1");

Option 2: construct the proper byte[] . Like,

InetAddress ip = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });

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