java - 客户端/服务器 java 故障 - 客户端在服务器上重新连接时发送多条消息
问题描述
我是编程新手,只要我成功打开我的服务器并在上面连接我的客户端。看来,当我用我的 actionPerformed 断开我的客户端并尝试重新连接时,消息被发送了两次。如果我再次这样做并第三次重新连接,则消息将发送 3 次。但是如果我关闭应用程序并重新启动它,没问题。谢谢您的帮助。
这是我的客户:
import java.io.*;
import java.net.*;
import java.awt.event.*;
import Control.fenetre;
import java.io.IOException;
public class Client implements ActionListener, Runnable {
private static Socket socket = null;
private static DataInputStream streamIn = null;
private static DataOutputStream streamOut = null;
private Thread thread = null;
boolean quitRequest = false;
int portSet;
String nickName;
String hostName;
public Client (String nickName, String hostName, int portSet) {
fenetre.boutonR1.addActionListener(this);
fenetre.fermerConnexion.addActionListener(this);
this.nickName = nickName;
this.hostName = hostName;
this.portSet = portSet;
try {
socket = new Socket(hostName, portSet);
start();
}
catch (IOException ioe) {
fenetre.statusBar.setText("Error.");
}
}
public void run() {
while (thread != null && quitRequest==false) {
try {
open();
boolean done = false;
while (!done) {
try {
String line = streamIn.readUTF();
fenetre.area.setText(fenetre.area.getText() + "\n\n"+line);
done = line.equals(".quit");
fenetre.statusBar.setText("Message recu");
fenetre.boiteVide();
}
catch(IOException ioe) {
done = true;
}
}
close();
}
catch(IOException ioe) {
fenetre.statusBar.setText("Connexion denied.");
}
}
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void open() throws IOException {
streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fenetre.boutonR1) {
try {
streamOut = new DataOutputStream(socket.getOutputStream());
streamOut.writeUTF(nickName+"\n" +fenetre.area.getText());
streamOut.flush();
fenetre.statusBar.setText("Message sent.");
}
catch (IOException e1) {
fenetre.statusBar.setText("Connexion issue.");
fenetre.boiteVide();
}
}
if (e.getSource() == fenetre.fermerConnexion) {
try {
close();
fenetre.statusBar.setText("Closing the connexion.\n");
fenetre.boiteVide();
}
catch (IOException ieo) {
fenetre.statusBar.setText("Fail.");
}
}
}
public void close() throws IOException {
quitRequest = true;
if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
if (streamOut != null) streamOut.close();
}
}
我用这个打开我的reconnexion:
private void ouvrirFil() {
Client porteClient = null;
porteClient = new Client(nickName, hostName, portSet);
}