import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.Scanner; public class Client { private BufferedReader in; private BufferedWriter out; private Socket socket; String userName; public Client(Socket socket, String username) { try { this.socket = socket; this.in = new BufferedReader(new InputStreamReader(socket.getInputStream())); this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); this.userName = username; } catch (IOException e) { closeEveryThing(in, out, socket); } } public void closeEveryThing(BufferedReader in, BufferedWriter out, Socket socket) { try { if (in != null) in.close(); if (out != null) out.close(); if (socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } } public void sendMessage() { try { out.write(userName); out.newLine(); out.flush(); Scanner sc = new Scanner(System.in); while (socket.isConnected()) { System.out.print("> "); String messageToSend = sc.nextLine(); out.write(userName + ": " + messageToSend); out.newLine(); out.flush(); } sc.close(); } catch (IOException e) { closeEveryThing(in, out, socket); } } public void listenForMessage() { Thread thread = new Thread(new Runnable() { @Override public void run() { String msgFromGroupChat; while (socket.isConnected()) { try { msgFromGroupChat = in.readLine(); System.out.println(msgFromGroupChat); } catch (IOException e) { closeEveryThing(in, out, socket); } } } }); thread.start(); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); System.out.print("Enter your username: "); String username = sc.nextLine(); Socket socket = new Socket("localhost" ,8512); Client client = new Client(socket, username); client.sendMessage(); client.listenForMessage(); sc.close(); } }