我最近在学习java socket 于是写了一个Server 和一个 Client的简单测试程序(下面会贴出代码),写完了之后,就找我另外的2个同学的笔记本电脑做测试。
我的电脑(A)作为服务器,其他2个同学的电脑(C,B)做客户端,前提:我们的笔记本电脑都用有线上网的,而且都能彼此ping的通的,这中情况下java socket程序运行正常。
当我们的笔记本都换成是无线上网的,并且都能彼此ping的通的,在这种情况下,他们(2个客户端)运行程序的时候就会出现
java.net.ConnectException: Connection timed out: connect这样的错误。
然后继续尝试,我的笔记本换成有线上网,他们2台机子是无线上网的,或者,我的是无线上网,他们的是有线上网,这2中情况java socket 程序都能正常运行(当然了,无线能ping通有线的电脑,而有线的电脑不能ping通无线的电脑)。
总的来说,就是客户端和服务端如果都是无线上网的话,那么java socket测试程序就不能正常通信,我想知道为什么,请大神赐教!!万分感激!!!!
下面是Server 和Client程序(这绝对是最简单的测试程序):
Server:
- Java code
import java.io.*;import java.net.*;public class Server extends ServerSocket { private static final int SERVER_PORT = 10000; public Server() throws IOException { super(SERVER_PORT); try { while (true) { Socket socket = accept(); new CreateServerThread(socket); } } catch (IOException e) { } finally { close(); } } // --- CreateServerThread class CreateServerThread extends Thread { private Socket client; private BufferedReader in; private PrintWriter out; public CreateServerThread(Socket s) throws IOException { client = s; in = new BufferedReader(new InputStreamReader(client.getInputStream(), "GB2312")); out = new PrintWriter(client.getOutputStream(), true); out.println("--- Welcome ---"); start(); } public void run() { try { String line = in.readLine(); while (!line.equals("bye")) { String msg = createMessage(line); out.println(msg); line = in.readLine(); } out.println("--- See you, bye! ---"); out.close(); in.close(); client.close(); } catch (IOException e) { } } private String createMessage(String line) { return "your input is:"+line; } } public static void main(String[] args) throws IOException { new Server(); }}
Client:
- Java code
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;import java.net.UnknownHostException;public class Client { private static Socket client; private static final int SERVER_PORT = 10000; private static BufferedReader in; private static PrintWriter out; private static String mesFormSer; public Client() throws Exception { client = new Socket("192.168.1.103", SERVER_PORT);//这里ip要看情况改 BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream(),true); System.out.println(in.readLine()); String message = sin.readLine(); while (!message.equals("Quit")) { out.println(message); this.mesFormSer = in.readLine(); System.out.println(this.mesFormSer); message = sin.readLine(); } in.close(); out.close(); sin.close(); client.close(); } public static void main(String args[]) { try { new Client(); } catch (Exception e) { e.printStackTrace(); } }}
------解决方案--------------------------------------------------------
这是传说中会出现的无线必须ping有线后,有线可以连几分钟,所以要用无线先ping下有线才能正常使用