ClientAppTest.java
unknown
java
a year ago
3.5 kB
3
Indexable
Never
import java.awt.Font; import java.io.*; import java.net.*; import java.util.Scanner; import javax.swing.*; public class ClientAppTest { public static void main(String[] args) { String serverAddress = "localhost"; int portNumber = 12345; Scanner s = new Scanner(System.in); System.out.println("Input port"); int port = s.nextInt(); s.close(); Thread inputThread = new Thread(() -> { ServerAppTest serverApp = new ServerAppTest(); serverApp.Connect(port); }); inputThread.start(); try (Socket clientSocket = new Socket(serverAddress, port); PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) { System.out.println("Connected to server"); JFrame frame = new JFrame("Client"); frame.setSize(1000, 1000); frame.setLayout (null); JLabel chatText = new JLabel ("Chat"); JTextArea incomingMessages = new JTextArea("newLabel"); JTextArea outgoingMessages = new JTextArea (5, 5); JButton sendButton = new JButton ("Send"); incomingMessages.setEditable(false); outgoingMessages.setToolTipText ("Send"); chatText.setBounds (295, 35, 210, 85); chatText.setFont (new Font("Arial", Font.BOLD, 20)); incomingMessages.setBounds (10, 55, 340, 430); outgoingMessages.setBounds (375, 60, 195, 385); sendButton.setBounds (410, 465, 100, 25); frame.add(chatText); frame.add(incomingMessages); frame.add(outgoingMessages); frame.add(sendButton); frame.setVisible(true); incomingMessages.setText(reader.readLine()); sendButton.addActionListener(e -> { String text = outgoingMessages.getText(); writer.println(text); outgoingMessages.setText(""); if (incomingMessages.getText().equals("Please enter your username:")) { incomingMessages.setText("Sucessfully singed up as: " + text + "! Enjoy the chat!"); } }); String message; while ((message = reader.readLine()) != null) { System.out.println(message); incomingMessages.setText(incomingMessages.getText() + "\n" + message); frame.repaint(); } /* Scanner scanner = new Scanner(System.in); System.out.println(reader.readLine()); // Server prompt for username String username = scanner.nextLine(); writer.println(username); // Send the username to the server Thread inputThread = new Thread(() -> { while (true) { String message = scanner.nextLine(); writer.println(message); } }); inputThread.start(); String message; while ((message = reader.readLine()) != null) { System.out.println(message); } */ } catch (IOException e) { e.printStackTrace(); } } }