2014-09-03 68 views
0
之间

采取以下基本程序:socket通信单独的机器

import java.io.*; 
import java.net.*; 

public class TestServer { 
    public static void main(String[] args) throws IOException { 
     ServerSocket listener = new ServerSocket(12345); 
     try { 
      while (true) { 
       Socket socket = listener.accept(); 
       try { 
        PrintWriter out = new PrintWriter(socket.getOutputStream(),true); 
        out.println(new java.util.Date().toString()); 
        out.close(); 
       } finally { 
        socket.close(); 
       } 
      } 
     } finally { 
      listener.close(); 
     } 
    } 
} 


public class TestClient { 
    public static void main(String[] args) { 
     try { 
      Socket socket = new Socket("0.0.0.0",12345); // Stack trace points to this line as the one with the error 
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
      System.out.println(in.readLine()); 
      in.close(); 
      socket.close(); 
     } catch (IOException e) { 
      System.err.println("IOException: " + e.getMessage()); 
     } 
    } 
} 

TestServer程序等待一个客户端连接到它,这样它可以发送信息,这一点,在这种情况下,当前的日期,给客户。在我的家用电脑(顺便说一句JCreator)中,我可以在同一台计算机上运行TestServer程序和TestClient程序,并获得所需的结果。问题是,当我运行不同的计算机上的TestClient程序并尝试连接到TestServer程序时,我不断收到消息IOException: Connection refused

有没有什么办法让这个工作?

+0

从您的问题中不清楚您是否将IP地址从“0.0.0.0”更改为远程计算机的IP地址 – 2014-09-03 13:20:09

回答

1

您正在尝试使用错误的IP地址连接到服务器(0.0.0.0)。

您需要知道运行服务器程序的计算机的IP地址,并使用它在客户端程序中实例化套接字。

请注意,应该可以从客户端计算机访问服务器。

+0

因此,每台计算机都有自己的IP地址? – TNT 2014-09-03 13:21:18

+0

是的,他们TNT – NightSkyCode 2014-09-03 13:21:34

+0

那么为什么'ServerSocket'类的'getInetAddress()'方法返回'0.0.0.0/0.0.0.0'? – TNT 2014-09-03 14:24:26