Wednesday, March 19, 2008

Simple Chat Client


package chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
* Here's a chat client (meant for two way or group chatting).
* It has two threads so it can simultaneously read
* what the server sends it, and can write and send to the server.
* Not included is the server code, which handles another client or group of clients.
* The server receives everything sent by the clients, and then sends it to every client
* to be written (which is why you see what you just said).
* It's very simple, and sort of the base of text communication over a server.
* It employs the java.net.Socket class, which uses the TCP protocol (meaning that 100% of
* packets are received in the order in which they were sent).
* @author amiller
*
*/
public class ChatClient {
//address and port information for all users
private static final int PORT = 1445;
private static final String SERVER_ADDRESS = "chatAddress";

private Socket socket;
private String userName;
private boolean isConnected;

public ChatClient(String usrName) throws UnknownHostException, IOException{
//string to identify user
userName = usrName;
//establish the connection and start the threads
establishConnection();
}

public void establishConnection() throws UnknownHostException, IOException{
//establishes communication with the server
socket = new Socket(SERVER_ADDRESS, PORT);
isConnected = true;

Writer writeThread = new Writer();
Reader readThread = new Reader();

//this starts the reading and the writing.
writeThread.start();
readThread.start();
}

/**
* To break from the while loops and kill the
* reader and writer threads
*/
public void disconnect(){
isConnected = false;
}

private class Reader extends Thread {
//reads from the socket connection
private BufferedReader reader;
public Reader() throws IOException{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
public void run(){
String lineFromServer;
while(isConnected){
lineFromServer = null;
try {
lineFromServer = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(lineFromServer != null)
System.out.println(lineFromServer);
}
}

}
private class Writer extends Thread {
//writes to socket
private PrintWriter writer;
//listens to the local computer's keyboard
private BufferedReader reader;

public Writer() throws IOException{
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(System.in));
}
/**
* This thread is constantly listening for the user's input (locally)
* When the user has entered a line, it writes it to the socket
* that has established a connection
*/
public void run(){
while(isConnected){
try {
String line = reader.readLine();
if(line != null)
writer.println(userName + ": " + line);
} catch(Exception e){
e.printStackTrace();
}
}
}
}

}

No comments: