Java - Data broadcasting

Server.java

import java.io.*;
import java.net.*;
import java.util.*;

public class Server implements Runnable {
ServerSocket serverSocket = null;
Socket socket = null;
ArrayList clientHandlerList = new ArrayList();
ClientHandler clientHandler = null;
BufferedReader readFromKeyboard = null;

public Server() {
try {
serverSocket = new ServerSocket(4444);
readFromKeyboard = new BufferedReader(
new InputStreamReader(System.in));
new Thread(this).start();

while(true) {
String message = readFromKeyboard.readLine();
broadcast(message);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
socket = serverSocket.accept();
clientHandler = new ClientHandler(socket, this);
clientHandlerList.add(clientHandler);
}
} catch(Exception exp) {
exp.printStackTrace();
}
}

public void broadcast(String message) {
ClientHandler client;
for(int i = 0; i < clientHandlerList.size() ; i++ ) {
client = (ClientHandler) clientHandlerList.get(i);
client.sendMessage(message);
}

}

public static void main(String[] args) {
new Server();
}
}


ClientHandler.java

import java.io.*;
import java.net.*;

public class ClientHandler {
Socket socket = null;
Server server = null;
PrintWriter writeToClient = null;

public ClientHandler(Socket socket, Server server) {
try {
this.socket = socket;
this.server = server;
writeToClient = new PrintWriter(socket.getOutputStream());
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void sendMessage(String message) {
writeToClient.println(message);
writeToClient.flush();
}
}


Client.java

import java.io.*;
import java.net.*;

public class Client implements Runnable {
Socket socket = null;
BufferedReader readFromServer = null;

public Client() {
try {
socket = new Socket("localhost", 4444);

readFromServer = new BufferedReader(
new InputStreamReader(socket.getInputStream()));

new Thread(this).start();

} catch(UnknownHostException exp) {
exp.printStackTrace();
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
String message = readFromServer.readLine();
System.out.println(message);
}
} catch(IOException ioExp) {
ioExp.printStackTrace();
}
}

public static void main(String[] args) {
new Client();
}
}

Post a Comment

0 Comments