Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Server.java
- package chatRoom;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.ArrayList;
- public class Server {
- private ServerSocket serverSocket;
- ArrayList<NewClient> clientArray = new ArrayList<NewClient>();
- int PORT = 4447;
- //int MAX = 30;
- public Server() throws IOException {
- serverSocket = new ServerSocket(PORT);
- System.out.println("Server Connected...");
- while (true) {
- Socket clientSocket = serverSocket.accept(); //accept new client
- NewClient newClient = new NewClient(this, clientSocket);
- newClient.start();
- // clientArray will be added after receiving message from client
- clientArray.add(newClient); // add client socket to ArrayList
- }
- }
- public void sendToAll(String msgFromClient) {
- }
- public static void main(String[] args) throws IOException {
- new Server();
- }
- }
- // NewClient.java
- package chatRoom;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.util.StringTokenizer;
- public class NewClient extends Thread {
- Socket clientSocket;
- Server server;
- BufferedReader in;
- PrintWriter out;
- String loginName = "";
- String loginIP = "";
- // LOGIN
- public NewClient(Server server, Socket clientSocket) throws IOException {
- this.server = server;
- this.clientSocket = clientSocket;
- in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
- out = new PrintWriter(clientSocket.getOutputStream());
- String loginInfo = in.readLine();
- // userName@/127.0.0.1 => (userName, userIP)
- StringTokenizer tok = new StringTokenizer(loginInfo, "@");
- loginName = tok.nextToken();
- loginIP = tok.nextToken();
- sendToMe("Welcome " + loginName + loginIP);
- // ==> send the list of chatters to clients <==
- // clientArray is not added in the beginning
- // is added after run()
- // new user
- //server.clientArray.add(this);
- if (server.clientArray.size() > 0) {
- String temp = "";
- for (NewClient newClient : server.clientArray) {
- temp += (newClient.loginName + newClient.loginIP) + "@";
- }
- // send other's login info to me
- sendToMe("USERLIST@" + server.clientArray.size() + "@" + temp);
- }
- // old user
- for (NewClient newClient : server.clientArray) {
- // send my login info to other
- newClient.sendToMe("ADD@" + loginName + loginIP);
- }
- }
- // RECEIVING MESSAGE
- public void run() {
- String msgFromClient = null;
- while (true) {
- try {
- // msgFromClient = username@ALL@hello world
- msgFromClient = in.readLine();
- if (msgFromClient.equals("CLOSE")) {
- in.close();
- out.close();
- clientSocket.close();
- for (NewClient newClient : server.clientArray) {
- newClient.sendToMe("DELETE@" + loginName);
- }
- server.clientArray.remove(this);
- return; // error without "return"
- } else {
- // msgFromClient = username@ALL@hello world
- StringTokenizer tok = new StringTokenizer(msgFromClient, "@");
- String sender = tok.nextToken();
- String receiver = tok.nextToken();
- String content = tok.nextToken();
- for (NewClient newClient : server.clientArray) {
- if (receiver.equals("ALL")) {
- if (!sender.equals(newClient.getUserName())) {
- msgFromClient = sender + ": " + content;
- newClient.sendToMe(msgFromClient);
- } else {
- msgFromClient = "Me" + ": " + content;
- sendToMe(msgFromClient);
- }
- } else if (!receiver.equals("ALL")) {
- if (newClient.getUserName().equals(receiver)) {
- msgFromClient = sender + ": " + content;
- newClient.sendToMe(msgFromClient);
- }
- }
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public void sendToMe(String msg) {
- out.println(msg);
- out.flush();
- }
- public String getUserName() {
- return loginName;
- }
- public String getUserIP() {
- return loginIP;
- }
- }
- // ChatGUI.java
- package chatRoom;
- import java.awt.event.KeyEvent;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.util.StringTokenizer;
- import javax.swing.DefaultListModel;
- import javax.swing.JOptionPane;
- /**
- *
- * @author jlee
- */
- public class ChatGUI extends javax.swing.JFrame {
- String hostIP = "127.0.0.1"; // server ip "localhost"
- int port = 4447;
- private Socket socket;
- private PrintWriter out;
- private BufferedReader in;
- private ReceiveMessage receiveMessage;
- private boolean isConnected = false;
- private DefaultListModel listModel;
- public ChatGUI() throws IOException {
- listModel = new DefaultListModel();
- initComponents();
- }
- @SuppressWarnings("unchecked")
- // <editor-fold defaultstate="collapsed" desc="Generated Code">
- private void initComponents() {
- buttonGroup = new javax.swing.ButtonGroup();
- inLogin = new javax.swing.JTextField();
- jScrollPane1 = new javax.swing.JScrollPane();
- outMessage = new javax.swing.JTextArea();
- btStart = new javax.swing.JButton();
- jScrollPane2 = new javax.swing.JScrollPane();
- userList = new javax.swing.JList(listModel);
- jPanel1 = new javax.swing.JPanel();
- btExit = new javax.swing.JButton();
- radioWisper = new javax.swing.JRadioButton();
- radioPublic = new javax.swing.JRadioButton();
- inMessage = new javax.swing.JTextField();
- btSend = new javax.swing.JButton();
- setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
- outMessage.setEditable(false);
- outMessage.setColumns(20);
- outMessage.setRows(5);
- jScrollPane1.setViewportView(outMessage);
- btStart.setText("Start");
- btStart.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- btStartActionPerformed(evt);
- }
- });
- userList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
- public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
- userListValueChanged(evt);
- }
- });
- jScrollPane2.setViewportView(userList);
- javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
- jPanel1.setLayout(jPanel1Layout);
- jPanel1Layout.setHorizontalGroup(
- jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGap(0, 0, Short.MAX_VALUE)
- );
- jPanel1Layout.setVerticalGroup(
- jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGap(0, 53, Short.MAX_VALUE)
- );
- btExit.setText("Exit");
- btExit.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- btExitActionPerformed(evt);
- }
- });
- buttonGroup.add(radioWisper);
- radioWisper.setText("Wisper");
- buttonGroup.add(radioPublic);
- radioPublic.setSelected(true);
- radioPublic.setText("Public");
- inMessage.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- inMessageActionPerformed(evt);
- }
- });
- inMessage.addKeyListener(new java.awt.event.KeyAdapter() {
- public void keyReleased(java.awt.event.KeyEvent evt) {
- inMessageKeyReleased(evt);
- }
- });
- btSend.setText("Send");
- btSend.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- btSendActionPerformed(evt);
- }
- });
- javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
- getContentPane().setLayout(layout);
- layout.setHorizontalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
- .addContainerGap()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
- .addGroup(layout.createSequentialGroup()
- .addComponent(inLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(btStart)
- .addGap(4, 4, 4)
- .addComponent(btExit, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGroup(layout.createSequentialGroup()
- .addComponent(inMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(btSend))
- .addGroup(layout.createSequentialGroup()
- .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(radioWisper)
- .addComponent(radioPublic))
- .addGap(0, 0, Short.MAX_VALUE))
- .addGroup(layout.createSequentialGroup()
- .addGap(4, 4, 4)
- .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))))
- .addGap(11, 11, 11)
- .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .addGap(0, 0, 0))
- );
- layout.setVerticalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addGap(10, 10, 10)
- .addComponent(inLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGroup(layout.createSequentialGroup()
- .addContainerGap()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(btExit)
- .addComponent(btStart))))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addGap(14, 14, 14)
- .addComponent(radioPublic)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .addComponent(radioWisper))
- .addComponent(jScrollPane1))
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addGap(0, 0, Short.MAX_VALUE)
- .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGroup(layout.createSequentialGroup()
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(inMessage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(btSend))
- .addContainerGap())))
- );
- pack();
- }// </editor-fold>
- private void inMessageActionPerformed(java.awt.event.ActionEvent evt) {
- send();
- }
- private void btSendActionPerformed(java.awt.event.ActionEvent evt) {
- send();
- }
- private void btExitActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- if (!isConnected) {
- JOptionPane.showMessageDialog(this, "Is not connected!",
- "", JOptionPane.ERROR_MESSAGE);
- return;
- }
- try {
- // close connection to server
- boolean flag = closeConnection();
- if (flag == false) {
- throw new Exception("Close error");
- }
- JOptionPane.showMessageDialog(this, "Bye.");
- } catch (Exception exc) {
- JOptionPane.showMessageDialog(this, exc.getMessage(),
- "", JOptionPane.ERROR_MESSAGE);
- }
- }
- private void inMessageKeyReleased(java.awt.event.KeyEvent evt) {
- // TODO add your handling code here:
- // if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
- // send();
- // }
- }
- private void btStartActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- if (isConnected) {
- JOptionPane.showMessageDialog(this, "isConnected",
- "", JOptionPane.ERROR_MESSAGE);
- return;
- }
- try {
- String name = inLogin.getText().trim();
- // ====> connect to server
- boolean flag = connectServer(port, hostIP, name);
- if (flag == false) {
- throw new Exception("Connection error");
- }
- this.setTitle(name);
- JOptionPane.showMessageDialog(this, "Welcome " + name);
- } catch (Exception exc) {
- JOptionPane.showMessageDialog(this, exc.getMessage(),
- "", JOptionPane.ERROR_MESSAGE);
- }
- }
- private void userListValueChanged(javax.swing.event.ListSelectionEvent evt) {
- // TODO add your handling code here:
- }
- //LOGIN
- public boolean connectServer(int port, String hostIP, String name) {
- try {
- socket = new Socket(hostIP, port);
- out = new PrintWriter(socket.getOutputStream());
- in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- //LOGIN
- // name@/x.x.x.x
- sendMessage(name + "@" + socket.getLocalAddress().toString());
- //receive message
- //receiveMessage = new ReceiveMessage(in, textArea);
- receiveMessage = new ReceiveMessage();
- receiveMessage.start();
- isConnected = true;
- return true;
- } catch (Exception e) {
- outMessage.append("Server port: " + port + "Server IP: " + hostIP + "\r\n");
- isConnected = false;
- return false;
- }
- }
- @SuppressWarnings("deprecation")
- public synchronized boolean closeConnection() {
- try {
- sendMessage("CLOSE");
- receiveMessage.stop(); //NullPointerException
- if (in != null) {
- in.close();
- }
- if (out != null) {
- out.close();
- }
- if (socket != null) {
- socket.close();
- }
- isConnected = false;
- System.exit(0);
- return true;
- } catch (IOException e1) {
- e1.printStackTrace();
- isConnected = true;
- return false;
- }
- }
- public void send() {
- if (!isConnected) {
- JOptionPane.showMessageDialog(this, "Is not connected!", "",
- JOptionPane.ERROR_MESSAGE);
- return;
- }
- String message = inMessage.getText().trim();
- if (message == null || message.equals("")) {
- JOptionPane.showMessageDialog(this, "No message", "",
- JOptionPane.ERROR_MESSAGE);
- return;
- }
- // username@ALL@hello world
- // sendMessage(this.getTitle() + "@" + "ALL" + "@" + message);
- if (radioWisper.isSelected()) {
- String receiver = (String) userList.getSelectedValue();
- sendMessage(this.getTitle() + "@" + receiver + "@" + message);
- } else {
- sendMessage(this.getTitle() + "@" + "ALL" + "@" + message);
- }
- inMessage.setText(null);
- }
- public void sendMessage(String message) {
- out.println(message);
- out.flush();
- }
- class ReceiveMessage extends Thread {
- public void run() {
- String msgFromServer = "";
- while (true) {
- try {
- // => CLOSE, ADD@, DELETE@, USERLIST@, MAX@, or username: hi
- msgFromServer = in.readLine();
- System.out.println(msgFromServer);
- // '/' or, '@'
- StringTokenizer tok = new StringTokenizer(msgFromServer, "/@");
- String command = tok.nextToken();
- // CLOSE
- if (command.equals("CLOSE")) {
- outMessage.append("Server closed!\r\n");
- removeUsers();
- return;
- } // MAX@username/x.x.x.x
- // else if (command.equals("MAX")) {
- // textArea.append("Max limited!\r\n");
- // removeUsers();
- // return;
- // }
- // DELETE@username
- else if (command.equals("DELETE")) {
- String username = tok.nextToken();
- listModel.removeElement(username);
- // ADD@username/x.x.x.x
- } else if (command.equals("ADD")) {
- String username = "";
- String userIp = "";
- if ((username = tok.nextToken()) != null
- && (userIp = tok.nextToken()) != null) {
- listModel.addElement(username);
- }
- // USERLIST@numOfUser@username@/x.x.x.x@username@/x.x.x.x
- } else if (command.equals("USERLIST")) {
- int numOfUser = Integer.parseInt(tok.nextToken());
- String username = null;
- String userIp = null;
- for (int i = 0; i < numOfUser; i++) {
- username = tok.nextToken();
- userIp = tok.nextToken();
- listModel.addElement(username);
- }
- // username: hello world
- } else {
- outMessage.append(msgFromServer + "\r\n");
- }
- } catch (IOException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public synchronized void removeUsers() throws Exception {
- listModel.removeAllElements();
- if (in != null) {
- in.close();
- }
- if (out != null) {
- out.close();
- }
- if (socket != null) {
- socket.close();
- }
- isConnected = false;
- }
- } // end of ReceiveMessage class
- public static void main(String args[]) {
- /* Set the Nimbus look and feel */
- //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
- /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
- * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
- */
- try {
- for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
- if ("Nimbus".equals(info.getName())) {
- javax.swing.UIManager.setLookAndFeel(info.getClassName());
- break;
- }
- }
- } catch (ClassNotFoundException ex) {
- java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (InstantiationException ex) {
- java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (IllegalAccessException ex) {
- java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (javax.swing.UnsupportedLookAndFeelException ex) {
- java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- }
- //</editor-fold>
- /* Create and display the form */
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- try {
- new ChatGUI().setVisible(true);
- } catch (IOException ex) {
- }
- }
- });
- }
- // Variables declaration - do not modify
- private javax.swing.JButton btExit;
- private javax.swing.JButton btSend;
- private javax.swing.JButton btStart;
- private javax.swing.ButtonGroup buttonGroup;
- private javax.swing.JTextField inLogin;
- private javax.swing.JTextField inMessage;
- private javax.swing.JPanel jPanel1;
- private javax.swing.JScrollPane jScrollPane1;
- private javax.swing.JScrollPane jScrollPane2;
- private javax.swing.JTextArea outMessage;
- private javax.swing.JRadioButton radioPublic;
- private javax.swing.JRadioButton radioWisper;
- private javax.swing.JList userList;
- // End of variables declaration
- }
- // Client.java
- package chatRoom;
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.GridLayout;
- import java.awt.Toolkit;
- 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.Socket;
- import java.util.StringTokenizer;
- import javax.swing.DefaultListModel;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JList;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.JScrollPane;
- import javax.swing.JSplitPane;
- import javax.swing.JTextArea;
- import javax.swing.JTextField;
- import javax.swing.border.TitledBorder;
- public class Client {
- private JFrame frame;
- private JList userList;
- private JTextArea textArea;
- private JTextField textField;
- private JTextField txt_port;
- private JTextField txt_hostIp;
- private JTextField txt_name;
- private JButton btn_start;
- private JButton btn_stop;
- private JButton btn_send;
- private JPanel northPanel;
- private JPanel southPanel;
- private JScrollPane rightScroll;
- private JScrollPane leftScroll;
- private JSplitPane centerSplit;
- private Socket socket;
- private PrintWriter out;
- private BufferedReader in;
- private ReceiveMessage receiveMessage;
- private boolean isConnected = false;
- private DefaultListModel listModel;
- public Client() {
- init();
- btn_start.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- int port;
- if (isConnected) {
- JOptionPane.showMessageDialog(frame, "isConnected",
- "", JOptionPane.ERROR_MESSAGE);
- return;
- }
- try {
- try {
- port = Integer.parseInt(txt_port.getText().trim());
- } catch (NumberFormatException e2) {
- throw new Exception("Port error");
- }
- String hostIp = txt_hostIp.getText().trim();
- String name = txt_name.getText().trim();
- if (name.equals("") || hostIp.equals("")) {
- throw new Exception("No Login");
- }
- // ====> connect to server
- boolean flag = connectServer(port, hostIp, name);
- if (flag == false) {
- throw new Exception("Connection error");
- }
- frame.setTitle(name);
- JOptionPane.showMessageDialog(frame, "Welcome " + name);
- } catch (Exception exc) {
- JOptionPane.showMessageDialog(frame, exc.getMessage(),
- "", JOptionPane.ERROR_MESSAGE);
- }
- }
- });
- btn_stop.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- if (!isConnected) {
- JOptionPane.showMessageDialog(frame, "Is not connected!",
- "", JOptionPane.ERROR_MESSAGE);
- return;
- }
- try {
- // close connection to server
- boolean flag = closeConnection();
- if (flag == false) {
- throw new Exception("Close error");
- }
- JOptionPane.showMessageDialog(frame, "I am leaving.");
- } catch (Exception exc) {
- JOptionPane.showMessageDialog(frame, exc.getMessage(),
- "", JOptionPane.ERROR_MESSAGE);
- }
- }
- });
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- if (isConnected) {
- // close connection to server
- closeConnection();
- }
- System.exit(0);
- }
- });
- textField.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent arg0) {
- send();
- }
- });
- btn_send.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- send();
- }
- });
- } // end of Client
- public void init() {
- textArea = new JTextArea();
- textArea.setEditable(false);
- textArea.setForeground(Color.blue);
- textField = new JTextField();
- txt_port = new JTextField("6666");
- txt_hostIp = new JTextField("127.0.0.1");
- txt_name = new JTextField("");
- btn_start = new JButton("Start");
- btn_stop = new JButton("Stop");
- btn_send = new JButton("Send");
- listModel = new DefaultListModel();
- userList = new JList(listModel);
- northPanel = new JPanel();
- northPanel.setLayout(new GridLayout(1, 7));
- northPanel.add(new JLabel("Port"));
- northPanel.add(txt_port);
- northPanel.add(new JLabel("IP"));
- northPanel.add(txt_hostIp);
- northPanel.add(new JLabel("Login"));
- northPanel.add(txt_name);
- northPanel.add(btn_start);
- northPanel.add(btn_stop);
- northPanel.setBorder(new TitledBorder(""));
- rightScroll = new JScrollPane(textArea);
- rightScroll.setBorder(new TitledBorder(""));
- leftScroll = new JScrollPane(userList);
- leftScroll.setBorder(new TitledBorder(""));
- southPanel = new JPanel(new BorderLayout());
- southPanel.add(textField, "Center");
- southPanel.add(btn_send, "East");
- southPanel.setBorder(new TitledBorder(""));
- centerSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftScroll,
- rightScroll);
- centerSplit.setDividerLocation(100);
- frame = new JFrame("");
- //frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Client.class.getResource("qq.png")));
- frame.setLayout(new BorderLayout());
- frame.add(northPanel, "North");
- frame.add(centerSplit, "Center");
- frame.add(southPanel, "South");
- frame.setSize(600, 400);
- int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width;
- int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height;
- frame.setLocation((screen_width - frame.getWidth()) / 2,
- (screen_height - frame.getHeight()) / 2);
- frame.setVisible(true);
- }
- //LOGIN
- public boolean connectServer(int port, String hostIp, String name) {
- try {
- socket = new Socket(hostIp, port);
- out = new PrintWriter(socket.getOutputStream());
- in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- //LOGIN
- // name@/x.x.x.x
- sendMessage(name + "@" + socket.getLocalAddress().toString());
- //receive message
- //receiveMessage = new ReceiveMessage(in, textArea);
- receiveMessage = new ReceiveMessage();
- receiveMessage.start();
- isConnected = true;
- return true;
- } catch (Exception e) {
- textArea.append("Server port: " + port + "Server IP: " + hostIp + "\r\n");
- isConnected = false;
- return false;
- }
- }
- @SuppressWarnings("deprecation")
- public synchronized boolean closeConnection() {
- try {
- sendMessage("CLOSE");
- receiveMessage.stop(); //NullPointerException
- if (in != null) { in.close(); }
- if (out != null) { out.close(); }
- if (socket != null) { socket.close(); }
- isConnected = false;
- return true;
- } catch (IOException e1) {
- e1.printStackTrace();
- isConnected = true;
- return false;
- }
- }
- public void send() {
- if (!isConnected) {
- JOptionPane.showMessageDialog(frame, "Is not connected!", "",
- JOptionPane.ERROR_MESSAGE);
- return;
- }
- String message = textField.getText().trim();
- if (message == null || message.equals("")) {
- JOptionPane.showMessageDialog(frame, "No message", "",
- JOptionPane.ERROR_MESSAGE);
- return;
- }
- // username@ALL@hello world
- sendMessage(frame.getTitle() + "@" + "ALL" + "@" + message);
- textField.setText(null);
- }
- public void sendMessage(String message) {
- out.println(message);
- out.flush();
- }
- class ReceiveMessage extends Thread {
- public void run() {
- String msgFromServer = "";
- while (true) {
- try {
- // => CLOSE, ADD@, DELETE@, USERLIST@, MAX@, or username: hi
- msgFromServer = in.readLine();
- System.out.println(msgFromServer);
- // '/' or, '@'
- StringTokenizer tok = new StringTokenizer(msgFromServer, "/@");
- String command = tok.nextToken();
- // CLOSE
- if (command.equals("CLOSE")) {
- textArea.append("Server closed!\r\n");
- removeUsers();
- return;
- }
- // MAX@username/x.x.x.x
- // else if (command.equals("MAX")) {
- // textArea.append("Max limited!\r\n");
- // removeUsers();
- // return;
- // }
- // DELETE@username
- else if (command.equals("DELETE")) {
- String username = tok.nextToken();
- listModel.removeElement(username);
- // ADD@username/x.x.x.x
- } else if (command.equals("ADD")) {
- String username = "";
- String userIp = "";
- if ((username = tok.nextToken()) != null
- && (userIp = tok.nextToken()) != null) {
- listModel.addElement(username);
- }
- // USERLIST@numOfUser@username@/x.x.x.x@username@/x.x.x.x
- } else if (command.equals("USERLIST")) {
- int numOfUser = Integer.parseInt(tok.nextToken());
- String username = null;
- String userIp = null;
- for (int i = 0; i < numOfUser; i++) {
- username = tok.nextToken();
- userIp = tok.nextToken();
- listModel.addElement(username);
- }
- // username: hello world
- } else {
- textArea.append(msgFromServer + "\r\n");
- }
- } catch (IOException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public synchronized void removeUsers() throws Exception {
- listModel.removeAllElements();
- if (in != null) { in.close(); }
- if (out != null) { out.close(); }
- if (socket != null) { socket.close(); }
- isConnected = false;
- }
- } // end of ReceiveMessage class
- public static void main(String[] args) {
- new Client();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment