2014-12-01 56 views
0

客户端代码当我运行客户端第一次服务器显示输出...当我运行客户端第二次,服务器不会不显示输出

try { 
    URL url=new URL("http://127.0.0.1:7655"); 
    HttpURLConnection connection=(HttpURLConnection) url.openConnection(); 
    connection.setDoOutput(true); 
    connection.connect(); 
    PrintWriter writer = new PrintWriter(connection.getOutputStream()); 
    writer.println("Hello"); 

    writer.flush(); 
    writer.close(); 
    connection.getResponseCode(); 
    connection.disconnect(); 
} catch (UnknownHostException e) { 
    System.err.println("Don't know about host: hostname"); 
} catch (IOException e) { 
    System.err.println("Couldn't get I/O for the connection to: hostname"); 
} 

服务器端代码

public static void main(String args[]) throws IOException { 
    ServerSocket echoServer = null; 
    String line; 
    DataInputStream is = null; 
    Socket clientSocket = null; 

    try { 
     echoServer = new ServerSocket(7655); 
     clientSocket = echoServer.accept(); 
     while (true) { 
      is = new DataInputStream(clientSocket.getInputStream());   
      System.out.println("inside"); 
      line = is.readLine(); 
      System.out.println(line); 
     } 
    }catch (IOException e) { 
     System.out.println(e); 
    }finally{ 
     is.close(); 
     clientSocket.close(); 
    } 
} 

当我第一次运行客户端时,服务器显示输出...第二次当我运行客户端时,服务器不显示输出。代码中有一些错误吗?

如果我没有找到最终服务器端的“Connection.getResponseCode”接收到null并在控制台上显示为null。为什么这是必要的?

回答

0

您的代码正是这样设计的。 您需要在服务器端使用多线程,线程接受所有连接,另一个是您的DataInputStream线程。

我是如何做到这一点的......我有一个类,它是自己的getters和setter,只用于线程之间需要的信息或数组。并且在您的主要运行中,将始终接受连接并读取每个连接的2个线程。

相关问题