我已经建立了一个 android TCP 连接,其中服务器是用 java 编写的,客户端是用 android 编写的。它基本上是一个服务器客户端聊天。代码一切正常,运行良好。问题是,当我关闭 android 客户端时,服务器忘记了客户端并且不再检索该客户端,但服务器和客户端都需要重新启动。我希望当我关闭客户端但服务器仍在运行时再次运行客户端,然后服务器应该搜索他最近的客户端并恢复服务器客户端聊天。我正在提供我的代码。请有人帮助尽快修改我的代码。谢谢
TCPServer.java
import javax.swing.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* The class extends the Thread class so we can receive and send messages at the same time */
public class TCPServer extends Thread {
public static final int SERVERPORT = 4444;
private boolean running = false;
private PrintWriter mOut;
private OnMessageReceived messageListener;
public static void main(String[] args) {
//opens the window where the messages will be received and sent
ServerBoard frame = new ServerBoard();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
/**
* Constructor of the class
* @param messageListener listens for the messages
*/
public TCPServer(OnMessageReceived messageListener) {
this.messageListener = messageListener;
}
/**
* Method to send the messages from server to client
* @param message the message sent by the server
*/
public void sendMessage(String message){
if (mOut != null && !mOut.checkError()) {
mOut.println(message);
mOut.flush();
}
}
@Override
public void run() {
super.run();
running = true;
try {
System.out.println("S: Connecting...");
//create a server socket. A server socket waits for requests to come in over network.
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
try {
//sends the message to the client
mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
//read the message received from client
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//in this while we wait to receive messages from client (it's an infinite loop)
//this while it's like a listener for messages
while (running) {
String message = in.readLine();
if (message != null && messageListener != null) {
//call the method messageReceived from ServerBoard class
messageListener.messageReceived(message);
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the ServerBoard
//class at on startServer button click
public interface OnMessageReceived {
public void messageReceived(String message);
} }