我已经按照一些教程创建了一个可以同时处理多个客户端的基本服务器。它正确接收数据,但它会消耗越来越多的内存,直到堆空间用完。我相信这是因为我的循环没有识别我的结束字符并离开了 for 循环。
这是接收数据的线程的代码:
while (true){
try {
is = new BufferedInputStream(s.getInputStream());
InputStreamReader isr = new InputStreamReader(is);
int character;
StringBuilder process = new StringBuilder();
try {
while((character = isr.read()) != 13) {
process.append((char)character); //here is the issue - it just continues to append until it runs out of memory
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parent.parent.writeToLog("Client " + Integer.toString(num) + " sent a message: " + process.toString());
System.out.println(process);
is = null;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedOutputStream os;
try {
os = new BufferedOutputStream(s.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write("Response from server at client socket " + Integer.toString(num) + " at " + (new java.util.Date()).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我在代码中添加了注释,它向我显示了堆栈跟踪上的错误。这是客户端,它只是 Java 教程中的 EchoClient:
import java.io.*;
import java.net.*;
import java.util.Random;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 2405);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
out.println("Message to host: hello" + (char) 13);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(Integer.toString((new Random()).nextInt()) + (char) 13);
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
您可以看到我将字符 13 附加到输出的位置,这就是结束循环的意思,但据我了解,这不起作用。谁能帮我解决这个问题?