networking - Communicating through two separate computer using java sockets -
i trying make chat server , client can communicate on 2 separate computers connected internet. 1 of them connected wifi , 1 through modem. here server code.
greetingserver.java
import java.net.*; import java.io.*; public class greetingserver extends thread { private serversocket serversocket; public greetingserver(int port) throws ioexception { serversocket = new serversocket(port); serversocket.setsotimeout(100000); } public void run() { while(true) { try { system.out.println("waiting client on port " + serversocket.getlocalport() + "..."); socket server = serversocket.accept(); system.out.println("just connected " + server.getremotesocketaddress()); datainputstream in = new datainputstream(server.getinputstream()); system.out.println(in.readutf()); dataoutputstream out = new dataoutputstream(server.getoutputstream()); out.writeutf("thank connecting " + server.getlocalsocketaddress() + "\ngoodbye!"); server.close(); }catch(sockettimeoutexception s) { system.out.println("socket timed out!"); break; }catch(ioexception e) { e.printstacktrace(); break; } } } public static void main(string [] args) { int port = integer.parseint("6066"); try { thread t = new greetingserver(port); t.start(); }catch(ioexception e) { e.printstacktrace(); } } }
greetingclient.java
import java.net.*; import java.io.*; public class greetingclient2 { public static void main(string [] args) { string servername = "10.2.3.100"; int port = integer.parseint("6066"); try { system.out.println("connecting " + servername + " on port " + port); socket client = new socket(servername, port); system.out.println("just connected " + client.getremotesocketaddress()); outputstream outtoserver = client.getoutputstream(); dataoutputstream out = new dataoutputstream(outtoserver); out.writeutf("hello " + client.getlocalsocketaddress()); inputstream infromserver = client.getinputstream(); datainputstream in = new datainputstream(infromserver); system.out.println("server says " + in.readutf()); client.close(); }catch(ioexception e) { e.printstacktrace(); } } }
the ip address in client code of computer server running acquired inetaddress.getlocalhost().gethostaddress(). when run server, waits client. , when run client code computer, doesn't connect. possible communicate through sockets in java ?
yes, possible. server has have external ip.
also if server connected via wifi, check router firewall settings.
Comments
Post a Comment