[英]Java: Set non-blocking reading from connected socket
大家好!!!!!!!!!! 我的代理/服務器以以下形式接收來自客戶端的請求:
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);
}
}
}
我在用#########分隔的塊中遇到問題。 我不知道如何在.readLine()中停止該方法。 首先,它讀取:GET mhttp:// proxy_ip:proxy_port / file.mhtml \\ n,然后讀取\\ n,但隨后阻塞,仍在等待讀取,但請求已完成。 我認為即使發送請求后,客戶端也可以保持連接狀態,但是我不能更改它,因為這是我老師的軟件。 我該如何解決?
不要讀整行,讀一個字節,直到遇到'\\n'
或按照Greg的建議執行2條讀線。 無論如何,由於您知道傳入消息的確切格式,因此請調整代碼以進行相應的閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.