Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.Socket;
- import java.util.Scanner;
- class ChatClient {
- static boolean finished1 = false;
- static class KeyboardHandler implements Runnable {
- PrintWriter pout = null;
- Scanner input = new Scanner(System.in);
- public KeyboardHandler(Socket server) throws IOException {
- OutputStream out = server.getOutputStream();
- pout = new PrintWriter(out, true);
- }
- public void run() {
- while(!ChatClient.finished1) {
- System.out.println("> ");
- String line = input.nextLine();
- if(line.equals("quit")) {
- ChatClient.finished1=true;
- }
- pout.println(line);
- }
- }
- }
- static class ResponseHandler implements Runnable {
- BufferedReader bin = null;
- public ResponseHandler(Socket server) throws Exception {
- InputStream in = server.getInputStream();
- bin = new BufferedReader( new InputStreamReader(in));
- }
- public void run() {
- while(!ChatClient.finished1) {
- String response;
- try {
- response = bin.readLine();
- System.out.println("Recieved Rx:");
- System.out.println(response);
- } catch (IOException ex) {
- if(!ChatClient.finished1){
- System.out.printf("Oh no! %s\n", ex.getMessage());
- }
- }
- }
- }
- }
- public static void main(String[] args) throws Exception {
- /**
- /* All of the resources which we must "clean up after" must be available in
- /* the `finally` block.
- */
- Socket server = null;;
- try {
- server = new Socket("127.0.0.1", 1234);
- KeyboardHandler kbHandler = new KeyboardHandler(server);
- ResponseHandler rxHandler = new ResponseHandler(server);
- Thread kbThread = new Thread(kbHandler);
- Thread rxThread = new Thread(rxHandler);
- kbThread.start();
- rxThread.start();
- kbThread.join();
- } catch(IOException e) {
- System.out.println(e.getMessage());
- } finally {
- if (server != null) {
- try {
- server.close();
- } catch (IOException e) {
- System.out.println(e.getMessage());
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement