You are on page 1of 3

public class Server implements AutoCloseable, Runnable{

private ServerSocket serverSocket;


public void stop() throws IOException{
if(this.serverSocket!=null){
this.serverSocket.close();
this.serverSocket=null;}}
@Override
public void close() throws Exception {
stop();}
public void start(int port) throws IOException{
this.serverSocket=new ServerSocket(port);
new Thread(this).start();}
@Override
public void run() {
while(!this.serverSocket.isClosed()){
try {
Socket socket=serverSocket.accept();
new Connection(socket);
} catch (IOException e) {
// TODO Auto-generated catch block
continue;}}}
public class Console {
public static void main(String[] args) {
try(Server server=new Server()){
int port=args.length==1?Integer.parseInt(args[0]):8080;
server.start(port);
System.out.println("Server is running");
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));

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();}}}}

You might also like