我在使用简单的 java 套接字客户端时遇到问题:连接已正确建立,服务器和客户端都接收和发送数据。当客户端失去连接几秒钟时,套接字完成并重新建立。这样做没问题,但是在那一刻,客户端(重新连接之前)收到的最后一条消息(在重新连接之前)再次无缘无故地收到(2 次接收相同的消息)。
我的代码是:
要启动套接字:
Socket sock = new Socket();
sock.bind(null);
InetSocketAddress isa = new InetSocketAddress(serverIPAddress,serverPort);
sock.connect(isa, conectionTimeOut);
sock.setKeepAlive(true);
InputStreamReader isR = new InputStreamReader(sock.getInputStream(), "UTF8");
reader = new BufferedReader(isR);
out = new BufferedWriter(new OutputStreamWriter(
sock.getOutputStream(), "UTF8"));
读取数据:
public class IncomingReader implements Runnable {
String message = "";
@Override
public void run() {
Thread thisThread = Thread.currentThread();
while (readerThread == thisThread) {
try {
while ((message = reader.readLine()) != null) {
manageServerMessage(message);
}
} catch (IOException e) {
Log.d(General.TAG, e.getMessage()+" "+e.getCause());
}
}
当连接丢失时:
public void stopSocket() {
readerThread = null;
try{
if (reader != null){
reader.close();
reader=null;
}
} catch (IOException e) {
Log.d(General.TAG, e.getMessage()+" "+e.getCause());
}
try{
if (out != null)
out.close();
} catch (IOException e) {
Log.d(General.TAG, e.getMessage()+" "+e.getCause());
}
try{
if (sock != null){
sock.close();
sock=null;
}
} catch (IOException e) {
Log.d(General.TAG, e.getMessage()+" "+e.getCause());
sock=null;
}
readerThread = null;
}