Saturday, March 5, 2011

Java - Public chat

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;

public Server() {
try {
serverSocket = new ServerSocket(4444);
new Thread(this).start();
} 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 sourceClient) {
ClientHandler client;
for(int i = 0; i < clientHandlerList.size() ; i++ ) {
client = (ClientHandler) clientHandlerList.get(i);
if (client != sourceClient) {
client.sendMessage(message);
}
}

}

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


ClientHandler.java


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

public class ClientHandler implements Runnable {
Socket socket = null;
Server server = null;
BufferedReader readFromClient = null;
PrintWriter writeToClient = null;

public ClientHandler(Socket socket, Server server) {
try {
this.socket = socket;
this.server = server;
readFromClient = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
writeToClient = new PrintWriter(socket.getOutputStream());

new Thread(this).start();
} catch(IOException exp) {
exp.printStackTrace();
}
}

public void run() {
try {
while(true) {
String message = readFromClient.readLine();
server.broadcast(message, this);
}
} 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 readFromClient = null;
BufferedReader readFromServer = null;
PrintWriter writeToServer = null;

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

readFromServer = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
writeToServer = new PrintWriter(socket.getOutputStream());
readFromClient = new BufferedReader(
new InputStreamReader(System.in));

new Thread(this).start();

while(true) {
String message = readFromClient.readLine();
writeToServer.println(message);
writeToServer.flush();
}
} 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();
}
}

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *