Jump to content
  • Advertisement
Sign in to follow this  
sss_1234

Simple Chat Server&Client

This topic is 2801 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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!=null)
if(users.isReady)
synchronized(users.out) {
users.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!=null)
if(users.isReady)
synchronized(users.out) {
users.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!=null)
if(users.isReady)
out.println("<"+users.ip+"> " + users.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==null)
(users = 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==this)
ChatServer.users = 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
Advertisement
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!