Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package chat;
- import java.awt.GridBagConstraints;
- import java.awt.GridBagLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.JScrollPane;
- import javax.swing.JTextArea;
- import javax.swing.JTextField;
- public class ChatClient {
- //communication variables
- BufferedReader in;
- PrintWriter out;
- String username;
- public static final int PORT = 9001;
- //GUI variables
- JFrame frame;
- JPanel panel;
- JTextField inputField;
- JTextArea messageArea;
- JButton clientButton;
- JButton serverButton;
- ChatServer localServer;
- ServerSocket listener;
- //create GUI
- public ChatClient () {
- //panel and layout manager
- panel = new JPanel(new GridBagLayout());
- GridBagConstraints c = new GridBagConstraints();
- //create and add input field
- c.gridwidth=2;
- c.fill = GridBagConstraints.HORIZONTAL;
- inputField = new JTextField(40);
- inputField.setEditable(false);
- //send text when enter is pressed and clear input field
- inputField.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- out.println(inputField.getText());
- inputField.setText("");
- }
- });
- panel.add(inputField, c);
- //create and add message area
- c.gridy=1;
- c.weighty=1;
- c.fill = GridBagConstraints.BOTH;
- messageArea = new JTextArea(8,40);
- messageArea.setEditable(false);
- panel.add(new JScrollPane(messageArea), c);
- //create and add "Connect" button
- c.gridy=2;
- c.gridwidth=1;
- c.fill = GridBagConstraints.HORIZONTAL;
- c.weightx=1;
- c.weighty=0;
- clientButton = new JButton("Connect to chatroom");
- //when pressed, connect to server on separate thread
- clientButton.addActionListener(new ActionListener() {
- public void actionPerformed (ActionEvent e) {
- if (in==null && out==null) {
- new Thread(new Runnable() {
- public void run() {
- receiveInput();
- }
- }).start();
- } else if (in!=null&&out!=null) {
- out.println("DISCONNECTING");
- }
- }
- });
- panel.add(clientButton, c);
- //create and add "Start server" button
- serverButton = new JButton("Start chatroom");
- serverButton.addActionListener(new ActionListener() {
- public void actionPerformed (ActionEvent e) {
- new Thread(new Runnable() {
- public void run() {
- //start server
- localServer = new ChatServer();
- new Thread(new Runnable() {
- public void run() {
- if (!localServer.running) {
- try {
- listener.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }).start();
- //new listener on port
- try {
- listener = new ServerSocket(PORT);
- //continuously accept new clients
- while (localServer.running) {
- localServer.new Handler(listener.accept()).start();
- }
- localServer = null;
- } catch (IOException serverException) {
- serverException.printStackTrace();
- } finally {
- try {
- listener.close();
- } catch (IOException e) {
- System.out.println("Couldn't close socket");
- }
- }
- }
- }).start();
- }
- });
- panel.add(serverButton, c);
- //create and show frame
- frame = new JFrame("George's Chat Program");
- frame.add(panel);
- frame.pack();
- frame.setLocationRelativeTo(null);
- frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- //when "X" pressed
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing (WindowEvent e) {
- if (in==null&&out==null) {
- System.exit(0);
- }
- out.println("DISCONNECTING");
- try {
- Thread.sleep(500);
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- }
- System.exit(0);
- }
- });
- frame.setVisible(true);
- }
- //get desired address from user
- private String getServerAddress () {
- return JOptionPane.showInputDialog(
- frame,
- "Enter IP Address of the Server:",
- "Welcome to George's Chat Program",
- JOptionPane.QUESTION_MESSAGE);
- }
- //get desired screen name from user
- private String getName () {
- return JOptionPane.showInputDialog(
- frame,
- "Choose a screen name:",
- "Screen name selection",
- JOptionPane.PLAIN_MESSAGE);
- }
- //connects to server then begins processing input
- private void receiveInput() {
- //Make connection and initialize streams (try-with-resources YES)
- try (Socket socket = new Socket(getServerAddress(), PORT)) {
- in = new BufferedReader(new InputStreamReader(
- socket.getInputStream()));
- out = new PrintWriter(socket.getOutputStream(), true);
- clientButton.setText("Disconnect from chatroom");
- serverButton.setEnabled(false);
- // Process all messages from server, according to the protocol.
- while (true) {
- String line = in.readLine();
- if (line.startsWith("SUBMITNAME")) {
- while ((username=getName())==null||username.equals("")) {
- JOptionPane.showMessageDialog(frame,"Username cannot be blank.");
- }
- out.println(username);
- } else if (line.startsWith("NAMEACCEPTED")) {
- inputField.setEditable(true);
- } else if (line.startsWith("MESSAGE")) {
- messageArea.append(line.substring(8) + "\n");
- } else if (line.startsWith("BYE")) {
- break;
- }
- }
- } catch (IOException e) {
- JOptionPane.showMessageDialog(frame, "No chat server is running at the specified address.");
- //server has closed or user has disconnected
- } finally {
- in = null;
- out = null;
- clientButton.setText("Connect to chatroom");
- serverButton.setEnabled(true);
- inputField.setEditable(false);
- messageArea.setText("");
- }
- }
- public static void main(String[] args) {
- new ChatClient();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment