Java for Programmers:
Lab 15
This is the client implementation for Lab 15. The server
implementation, which you don't need to create, is here.
The Lab Instructions are:
1. Create a ChatClient Class. Chat Client will:
- Have a main method
- Set a username variable based on a program argument
- Create a new Socket
- Create and start two new Threads: ReaderThread and
WriterThread
2. Create a WriterThread class. It will:
- Supply a contructor that will take a name [String]
and a Socket
- Create a BufferedReader to read from System.in
- Create a PrintWriter to write to the Socket.
- Supply a while loop that reads from Standard Input
and writes to the Socket. The message received from Standard
Input should prepend the username to itself, plus a >,
so that the message sent to the Socket takes the form:
username> Message Typed.
3. Create a ThreadReader class that:
- Supplies a Constructor which takes a Socket.
- Creates a continuous loop that reads from the Socket
and prints out the value written [System.out.println]
import java.net.Socket; import java.io.*;
public class ChatClient {
public static void main(String[] args) { String name = "Anonymous";
if (args.length > 0) { name = args[0]; }
try {
Socket sock = new Socket("204.49.73.220", 2424); Thread t = new Thread(new ReadThread(sock)); Thread t2 = new Thread(new WriteThread(sock, name)); t.start(); t2.start();
}
catch(Exception e) { e.printStackTrace(); }
}
}
class WriteThread implements Runnable {
Socket sock; String name;
public void run() { try {
PrintWriter out = new PrintWriter(new OutputStreamWriter(sock.getOutputStream())); BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
while (true) { String lineVal;
if ((lineVal = inStream.readLine()) != null) { out.println(name+"> "+lineVal); out.flush(); }
}
}
catch(Exception e) {
e.printStackTrace();
}
}
WriteThread(Socket sock, String name) { this.sock = sock; this.name = name; }
}
class ReadThread implements Runnable { Socket sock;
public void run() { try { while (true) { BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream())); String s = br.readLine(); System.out.println(s); } } catch(Exception e) {
e.printStackTrace();
} } ReadThread(Socket sock) { this.sock = sock; } } |