Sign in to follow this  
sss_1234

Simple Chat Server&Client

Recommended Posts

I've just finished writing a simple chat server&client in Java.
Server is text-based, the client has a Swing GUI.

Here's the source code for the server:


package server;

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;

public class ChatServer {

static final int MAX_USERS = 100;
static final int PORT = 4448;

static ServerSocket server = null;
static ClientHandler[] users = new ClientHandler[MAX_USERS];

static void announce(String message) {
System.out.println(message);
for(int i=0;i<MAX_USERS;i++)
if(users[i]!=null)
if(users[i].isReady)
synchronized(users[i].out) {
users[i].out.println(message);
}
}

static void sendMessage(String ip, String nick, String message) {
String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
System.out.println(time+" <"+ip+"> " + nick + ": " + message);
for(int i=0;i<MAX_USERS;i++)
if(users[i]!=null)
if(users[i].isReady)
synchronized(users[i].out) {
users[i].out.println(time+" <"+ip+"> " + nick + ": " + message);
}
}

static void sendOnline(PrintWriter out) {
synchronized(out) {
out.println();
out.println("*** Now online: ***");
for(int i=0;i<MAX_USERS;i++)
if(users[i]!=null)
if(users[i].isReady)
out.println("<"+users[i].ip+"> " + users[i].nick);
}
out.println();
}

static void error(Exception e) {
System.out.println("An error occured. Details:");
System.out.println("Message: "+e.getMessage());
System.out.println("Stack Trace:");
System.out.println(e.getStackTrace());
}

public static void main(String[] args) throws IOException {
System.out.println("Chat Server is running.");

try {
System.out.println("trying to listen to port "+PORT+"...");
server = new ServerSocket(PORT);
System.out.println("Listening to port "+PORT);

while(true) {
for(int i=0;i<MAX_USERS;i++)
if(users[i]==null)
(users[i] = new ClientHandler(server.accept())).start();
Thread.sleep(500);
}

} catch (Exception e) {
error(e);
} finally {
System.out.println("Terminates...");
if(server!=null) server.close();
System.out.println("Terminated successfully");
}
}
}






package server;

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

public class ClientHandler extends Thread {

Socket client = null;
String ip, nick;
BufferedReader in = null;
PrintWriter out = null;
boolean isReady = false;

ClientHandler(Socket client) throws IOException {
isReady = false;
this.client = client;
}

private void help() {
synchronized(out) {
out.println();
out.println("*** Commands: ***");
out.println("*** #quit - disconnect from server ***");
out.println("*** #help - show commands ***");
out.println("*** #online - show who's online ***");
out.println();
}
}

public void run() {
String request;

try {
ip = client.getInetAddress().getHostAddress();
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(client.getInputStream()));

out.println("*** Welcome to Chat Server ***");
out.println("*** Please choose a nickname ***");
nick = in.readLine();
out.println("*** Hello, "+nick+". ***");
help();

ChatServer.announce("*** New User Connected: <"+ip+"> "+nick+" ***");
isReady = true;
while(true) {
request = in.readLine();
if(request.equalsIgnoreCase(""))
continue;
if(request==null||request.equalsIgnoreCase("#quit"))
break;
if(request.equalsIgnoreCase("#help")) {
help();
continue;
}
if(request.equalsIgnoreCase("#online")) {
ChatServer.sendOnline(out);
continue;
}
ChatServer.sendMessage(ip, nick, request);
}
isReady = false;
out.println("*** Thank you for using the Chat Server. ***");
out.println("*** Goodbye! ***");

} catch (IOException e) {
ChatServer.error(e);
} finally {
try {
if(in!=null) in.close();
if(out!=null) out.close();
if(client!=null) client.close();
} catch (IOException e) {

} finally {
for(int i=0;i<ChatServer.MAX_USERS;i++)
if(ChatServer.users[i]==this)
ChatServer.users[i] = null;
ChatServer.announce("*** User Left: <"+ip+"> "+nick+" ***");
}
}
}

}



And... the source code for the client:



import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class ChatClient extends JFrame implements WindowListener, ActionListener {

JPanel mainCP;
JScrollPane chatScroll;
JTextArea chatHistory;
JTextField chatTextField;
JLabel inputLabel;

String ip;

Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;

boolean waitingForAdd = true;

ChatClient() {
waitingForAdd = true;
this.setTitle("Chat Client");
this.setSize(500,300);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(this);

mainCP = new JPanel(null);

chatHistory = new JTextArea("");
chatHistory.setEditable(false);
inputLabel = new JLabel("type here:");
inputLabel.setBounds(5,245,60,20);
chatTextField = new JTextField("");
chatTextField.setBounds(5+60, 245, 480-60, 20);

chatScroll = new JScrollPane(chatHistory);
chatScroll.setBounds(5, 5, 480, 235);
mainCP.add(chatScroll);
mainCP.add(inputLabel);
mainCP.add(chatTextField);

this.setContentPane(mainCP);
chatTextField.addActionListener(this);
this.setVisible(true);
}

void setIP(String ip) {
this.ip = ip;
}

void connect() throws IOException, UnknownHostException {
addToChatHistory("Trying to connect to "+ip+"...");
socket = new Socket(ip, 4448);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
addToChatHistory("Connected!\n");
}

void addToChatHistory(String string) {
chatHistory.append(string+"\n");
chatHistory.setCaretPosition(chatHistory.getDocument().getLength());
}

void disconnect() {
addToChatHistory("Trying to disconnect...");
try {
if(in!=null) in.close();addToChatHistory("in disconnected");
if(out!=null) out.close();addToChatHistory("out disconnected");
if(socket!=null) socket.close();addToChatHistory("socket disconnected");
addToChatHistory("Disconnected successfully!");
} catch (IOException e) {
addToChatHistory("An error occured while trying to disconnect.");
}
}

public void windowDeiconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void actionPerformed(ActionEvent e) {
String text = chatTextField.getText();
if(waitingForAdd) {
setIP(text);
waitingForAdd = false;
} else {
out.println(text);
}
chatTextField.setText("");
}

public void windowClosing(WindowEvent e) {
//nothing
}

public void windowIconified(WindowEvent e) {}

public static void main(String args[]) {
String query;
ChatClient chatClient = new ChatClient();
chatClient.addToChatHistory("Please enter the address of the server.");
while(chatClient.waitingForAdd) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
try {
chatClient.connect();
while(true) {
query = chatClient.in.readLine();
if(query==null) break;
chatClient.addToChatHistory(query);
}
} catch (UnknownHostException e) {
chatClient.addToChatHistory("Unknown Host Exception oocured!");
} catch (IOException e) {
chatClient.addToChatHistory("IOException occured");
} finally {
chatClient.disconnect();
chatClient.dispose();
}
}
}



Note (dirty programming):
I should have used notifyAll()/wait() instead of Thread.sleep(ms), but it made some annoying errors so I used the "dirty" way. (Don't tell anyone ;-)

Share this post


Link to post
Share on other sites
Sign in to follow this