Client
Client main file.unknown
java
4 years ago
2.9 kB
2
Indexable
package client; import java.io.DataOutputStream; import java.io.IOException; import java.io.DataInputStream; import java.net.InetAddress; import java.net.Socket; import java.util.Scanner; public class Client { private Socket socket; private DataInputStream input; private DataOutputStream output; private Scanner scanner; private final String serverMessageOne = "Server: write your name"; private final String serverMessageTwo = "Server: This name is already taken! Choose another one."; private boolean quite = false; public Client() throws Exception { socket = new Socket(InetAddress.getLocalHost(), 4444); System.out.println("Client started!"); input = new DataInputStream(socket.getInputStream()); output = new DataOutputStream(socket.getOutputStream()); scanner = new Scanner(System.in); setName(); // getting user unique name; Thread thread = new Thread() { @Override public void run() { String message; try { while (true) { message = input.readUTF(); System.out.println(message); } } catch (Exception e) { try { socket.close(); output.close(); input.close(); } catch (IOException e1) { e1.printStackTrace(); } } } }; thread.start(); Thread thread2 = new Thread() { @Override public void run() { String message; try { while (!quite) { message = scanner.nextLine(); output.writeUTF(message); if (message.equals("/exit")) { System.out.println("Server exit: "); exitConnection(); } } } catch (Exception e) { try { socket.close(); output.close(); input.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }; thread2.start(); } public synchronized void setName() { try { while (true) { String message = input.readUTF(); System.out.println(message); if (message.contains(serverMessageOne) || message.contains(serverMessageTwo)) { String name = scanner.nextLine(); output.writeUTF(name); } else { break; } } } catch (Exception e) { e.printStackTrace(); } } public synchronized void exitConnection() { try { quite = true; closeConnection(); return; } catch (Exception e) { e.printStackTrace(); } } public void closeConnection() throws Exception { socket.close(); output.close(); input.close(); } public static void main(String[] args) { try { new Client(); } catch (Exception e) { e.printStackTrace(); } } }
Editor is loading...