2013-02-25 84 views
0

大家好!!!!!!!!!! 我的代理/服务器从客户端以这种形式接收请求:Java:从连接的套接字中设置无阻塞读取

GET mhttp://proxy_ip:proxy_port/file.mhtml\n 
\n 

,这里是我的代码:

import java.io.*; 
import java.net.Socket; 
import java.net.ServerSocket; 
import java.net.InetAddress; 
import java.net.UnknownHostException; 

public class ProxyMain { 

public static void main(String argv[]) { 

    int proxyPort = 55554; 
    String proxyAddr = "127.0.0.1"; 
    ServerSocket proxySocket = null; 

    try { 
     proxySocket = new ServerSocket(proxyPort, 50, InetAddress.getByName("127.0.0.1")); 
    } 

    catch (Exception e) { 
     System.err.println("Impossible to create socket server!"); 
     System.out.flush(); 
     System.exit(1); 
    } 

    System.out.printf("Server active on port: %d and on address %s\n", proxyPort, proxySocket.getInetAddress()); 

    while (true) { 
     Socket client = null; 
     BufferedReader in = null; 
     PrintWriter out = null; 
     String request = new String(); 
     String tmp = new String(); 


     try { 
      client = proxySocket.accept(); 
      System.out.println("Connected to: "); 
      System.out.println(client.getInetAddress().toString()); 
      System.out.printf("On port %d\n", client.getPort()); 
      in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
      out = new PrintWriter(client.getOutputStream(), true); 

     } 

     /*catch (IOException e) { 
      System.err.println("Couldn't get I/O for connection accepted"); 
      System.exit(1); 
     }*/ 

     catch (Exception e) { 
      System.out.println("Error occurred!"); 
      System.exit(1); 
     } 

     System.out.println("Received request:"); 

     try{ 
      ##################################### 
          while ((tmp = in.readLine()) != null) 
      System.out.println(tmp); 
      request = request + tmp; 
          ##################################### 
     } 
     catch (IOException ioe) { 
      System.err.println("Impossible to read mhttp request!"); 
      System.exit(1); 
     } 

     System.out.println(request); 
    } 

} 

} 

我有#########分隔块问题。 我不知道如何停止in.readLine()方法。 首先它读取: GET mhttp:// proxy_ip:proxy_port/file.mhtml \ n 然后它读取 \ n 但它然后阻止,仍然等待阅读但请求完成。 我认为即使在发送请求后,客户端仍然保持连接正常,但我无法更改,因为它是我的老师的软件。 我该如何解决这个问题?

+1

看看:http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedInputStream.html#available%28%29 – 2013-02-25 14:00:34

+1

为什么你在循环中读取if你知道你只需要阅读'2'行?只需执行2'readLine()'调用...? – 2013-02-25 14:04:47

+0

我在想,最好是执行普通的purpouse代理...以接受任何类型的请求 – user1576208 2013-02-25 14:18:40

回答

1

不会读取整行,请阅读单个字节,直到遇到'\n'或执行2条readlines,如Greg所示。在任何情况下,由于您知道传入消息的确切格式,请调整您的代码以相应阅读。