Projet_POO/Projet_POO/src/reseau/TCPServerThread.java

79 lines
1,8 KiB
Java

package reseau;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class TCPServerThread extends TCPClient implements Runnable{
Thread thread;
boolean terminé = false;
List<String> messages = new ArrayList<String>();
public TCPServerThread(Socket socket, boolean start) {
super(socket);
if (start) {
thread = new Thread(this);
thread.start();
}
}
public TCPServerThread(String host, int port, boolean start) {
super(host,port);
if (start) {
thread = new Thread(this);
thread.start();
}
}
public void stop() {
this.terminé = true;
try {
this.socket.close();
}
catch (IOException e) {
System.out.print("Error while closing connection\n");
}
}
public void setMessages(String message) {
List<String> newMessages = new ArrayList<String>(this.messages);
newMessages.add(message);
this.support.firePropertyChange("messages", this.messages, newMessages);
this.messages = newMessages;
}
public void run() {
while (!terminé) {
try {
String message = this.receive();
setMessages(message);
if (message != null) {
System.out.print("Status : " + terminé + ", message reçu : " + message + "\n");
}
else {
//La connexion a été interrompue
this.terminé = true;
}
}
catch (IOException e) {
this.terminé = true;
System.out.print("Connection sur le port " + this.port + " vers " + this.adresseCible +" interrompue.\n");
}
catch (Exception e) {
this.terminé = true;
System.out.print(e);
}
}
this.stop();
}
}