Java:从连接的套接字设置非阻塞读取

时间:2013-02-25 13:54:34

标签: 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 个答案:

答案 0 :(得分:1)

不读取整行,读取单个字节,直到遇到'\n'或执行2条读取线,如Greg建议的那样。在任何情况下,由于您知道传入消息的确切格式,因此请调整代码以进行相应的读取。