0
votes

I have created a simple game, that two computer connect together. I have tested on same computer, no problem. When I create ad-hoc network (in Windows 7). One computer is a server, it created successfully :

ssock = new ServerSocket(PORT);
sock = ssock.accept();

And one computer is client:

sock = new Socket("localhost", PORT);

When run to this line. I received this error :

java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at java.net.Socket.connect(Socket.java:478) at java.net.Socket.(Socket.java:375) at java.net.Socket.(Socket.java:189) at com.controller.MainController$GameObject.(MainController.java:78) at com.controller.MainController$3.run(MainController.java:180) at java.lang.Thread.run(Thread.java:662)

Please help me point out, what wrong here.

Thanks :)

2
Is there a firewall (OS firewall or network firewall) in between? Is server reachable?SJuan76
With what did you replace the hostname "localhost" on the client when you transfered the server to another machine? ("localhost" means "this machine", not "a machine on the local network")Philipp
@Philipp I don't understand you so much. Does it means we shouldn't use localhost but other name ?hqt
@SJuan76 how to know server reachable ? But, when I connect ad-hoc of these two computer, I can play another game together, does it matter ? thanks :)hqt
Yes, 'localhost' is the name of this host. If you want to talk to another host you have to use its name, not your own.user207421

2 Answers

1
votes

In the line

sock = new Socket("localhost", PORT); 

the first argument "localhost" is the hostname of the machine you want to connect to. "localhost" always means the current machine. When the server runs on another machine, you have to tell the socket where to find it.

You need to replace "localhost" with the IP address or the hostname of the other machine. When you don't know these, follow these steps on the server machine:

  • Start -> Run
  • enter cmd and press enter to open the command shell
  • enter ipconfig in the command shell and press enter

You will now see configuration information about all network adapters on the machine, including their IP addresses.

0
votes

In addition to replacing "localhost" by desired IP address you myst remrmber to check if pointed ports are opoened on firewalls.