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 但它然後阻止,仍然等待閱讀但請求完成。 我認爲即使在發送請求後,客戶端仍然保持連接正常,但我無法更改,因爲它是我的老師的軟件。 我該如何解決這個問題?
看看:http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedInputStream.html#available%28%29 – 2013-02-25 14:00:34
爲什麼你在循環中讀取if你知道你只需要閱讀'2'行?只需執行2'readLine()'調用...? – 2013-02-25 14:04:47
我在想,最好是執行普通的purpouse代理...以接受任何類型的請求 – user1576208 2013-02-25 14:18:40