Professional Documents
Culture Documents
while(true){
try{
String message=reader.readLine();
if(message==null || "exit".equalsIgnoreCase(message)){
break;}
}catch(Exception e){
break;}}
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());}}}
public class Connection implements Runnable {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
private static List<Connection> connections=new ArrayList<Connection>();
public Connection(Socket socket) {
try {
this.socket=socket;
this.reader=new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.writer=new PrintWriter(this.socket.getOutputStream(), true);
new Thread(this).start();
} catch (IOException e) {
e.printStackTrace();}}
@Override
public void run() {
synchronized(connections){
connections.add(this);
}
while(!socket.isClosed()){
try {
String message = null;
message = reader.readLine();
if(message!=null){
broadcast(message);}
} catch (IOException e) {
break;}}
synchronized(connections){
connections.remove(this);}}
private void broadcast(String message) {
synchronized(connections){
for(Connection connection:connections){
connection.writer.println(message);
connection.writer.flush();}}}}