我正在尝试实现一个简单的服务器(java 应用程序)和客户端(android 应用程序),其中客户端每秒发送一个字符串大约 10 次。一切正常运行一分钟左右,之后服务器停止接收来自客户端的消息。相关代码如下。
ClientThread.java
public class ClientThread implements Runnable{
static Socket socket;
static String message = "";
InetAddress serverAddr;
BufferedOutputStream bos;
public ClientThread(String message){
ClientThread.message = message;
}
@Override
public void run() {
try{
serverAddr = InetAddress.getByName(SERVER_IP);
if(socket != null && socket.isConnected())socket.close();
socket = new Socket(serverAddr, SERVER_PORT);
bos = new BufferedOutputStream (socket.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
osw.write(message);
osw.flush();
socket.shutdownOutput();
socket.close();
}catch (Exception e) {
}
}
}
服务器线程.java
public class ServerThread extends Thread{
private ServerSocket serverSocket;
static String clientSentence;
public ServerThread(int port) throws IOException, AWTException{
serverSocket = new ServerSocket(port);
}
public void run() {
while(true){
try{
Socket server = serverSocket.accept();
BufferedReader d = new BufferedReader(new InputStreamReader(server.getInputStream()));
clientSentence = d.readLine();
System.out.println(clientSentence);
server.close();
}catch(IOException e){
e.printStackTrace();
break;
}
}
}
}
ClientThread.java 每秒调用大约 10 次,使用:
Thread clientThread = new Thread(new ClientThread(message));
clientThread.start();
ServerThread.java 使用以下命令初始化和启动:
t = new ServerThread(8888);
t.start();
关于为什么运行一段时间后会冻结的任何想法?修复它的唯一方法是重新启动服务器,然后一分钟后再次出现同样的问题。我花了很多时间研究这个问题,但无法找到解决方案。
编辑:我发现服务器冻结在 clientSentence = d.readLine(); 部分。知道为什么吗?