天天看點

JAVA進階案例 TCP程式設計之網絡聊天工具(用戶端)

首先附上登入操作

JAVA進階案例 TCP程式設計之網絡聊天工具(用戶端)

登入界面就不說了,直說業務處理。當點選登入之後

/*
     * 如果點選了登入按鈕 首先判斷帳号或者密碼是否為空 然後封裝為CommandTranser對象 向伺服器發送資料 伺服器通過與資料庫的比對
     * 來驗證帳号密碼
     */
    if (e.getSource() == login) {
      String username = text_name.getText().trim();
      String password = new String(text_pwd.getPassword()).trim();
      if ("".equals(username) || username == null) {
        JOptionPane.showMessageDialog(null, "請輸入帳号!!");
        return;
      }
      if ("".equals(password) || password == null) {
        JOptionPane.showMessageDialog(null, "請輸入密碼!!");
        return;
      }
      User user = new User(username, password);
      CommandTranser msg = new CommandTranser();
      msg.setCmd("login");
      msg.setData(user);
      msg.setReceiver(username);
      msg.setSender(username);
      // 執行個體化用戶端 并且發送資料 這個client用戶端 直到程序死亡 否則一直存在
      Client client = new Client();
      client.sendData(msg);
      msg = client.getData();
      if (msg != null) {
        if (msg.isFlag()) {
          this.dispose();
          JOptionPane.showMessageDialog(null, "登陸成功!");
          // 顯示好友清單界面
          new FriendsUI(username, client);
        } else {
          JOptionPane.showMessageDialog(this, msg.getResult());
        }
      }

    } else if (e.getSource() == sweep) {
      text_name.setText(null);
      text_pwd.setText(null);
    }

  }      

把帳号密碼 登入指令等封裝為CommandTranser對象  然後執行個體化一個用戶端  通過

sendData(CommandTranser msg)

 方法向伺服器發送資料 然後通過getData方法獲得伺服器傳回的資料。

其中CommandTranser類在服務端已經介紹 主要變量如下

private String sender = null;// 發送者
  private String receiver = null;// 接受者
  private Object data = null;// 傳遞的資料
  private boolean flag = false;// 指令的處理結果
  private String cmd = null;// 服務端要做的指令
  private String result = null;// 處理結果      

用戶端Client代碼主要負責向服務端發送資料 sendData(CommandTranser msg) 和接收服務端的資料 getData()

構造方法

// 執行個體化時 建立連接配接
  public Client() {
    try {
      socket = new Socket(address, port);
    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      JOptionPane.showMessageDialog(null, "服務端未開啟");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      JOptionPane.showMessageDialog(null, "服務端未開啟");
    }
  }      

sendData(CommandTranser msg)

 方法

// 向服務端發送資料
  public void sendData(CommandTranser msg) {
    ObjectOutputStream oos = null;
    try {
      if (socket == null)
        return;
      oos = new ObjectOutputStream(socket.getOutputStream());
      oos.writeObject(msg);
    } catch (UnknownHostException e1) {
      JOptionPane.showMessageDialog(null, "服務端未開啟");
    } catch (IOException e1) {
      JOptionPane.showMessageDialog(null, "服務端未開啟");
    }
  }      

 getData()方法

// 向服務端接收資料
  public CommandTranser getData() {
    ObjectInputStream ois = null;
    CommandTranser msg = null;
    if (socket == null)
      return null;
    try {
      ois = new ObjectInputStream(socket.getInputStream());
      msg = (CommandTranser) ois.readObject();
    } catch (IOException e) {
      return null;
    } catch (ClassNotFoundException e) {
      return null;
    }
    if ("message".equals(msg.getCmd()))
      System.out.println((String) msg.getData());
    return msg;
  }      

如果伺服器傳回登入成功的消息 則進入好友清單界面

JAVA進階案例 TCP程式設計之網絡聊天工具(用戶端)

在登入界面 所有的好友都是我自己建立的  。陌生人知識一個擺設。。當然也可以通過服務端的資料庫來加載好友清單。。以後自己慢慢更新  

這兩天出現的各種各樣的錯誤 頭都炸了。。

而在好友界面  有一個滑鼠輕按兩下事件  和滑鼠進入好友清單,離開好友清單事件

JAVA進階案例 TCP程式設計之網絡聊天工具(用戶端)

當滑鼠進入好友清單 改變背景色

// 如果滑鼠進入我的好友清單 背景色變色
    @Override
    public void mouseEntered(MouseEvent e) {
      // TODO Auto-generated method stub
      JLabel label = (JLabel) e.getSource();
      label.setOpaque(true);
      label.setBackground(new Color(255, 240, 230));
    }      

修改背景色之前  一定要設定為不透明  label.setOpaque(true);

不然看不到背景色

滑鼠離開好友清單

// 如果滑鼠退出我的好友清單 背景色變色
    @Override
    public void mouseExited(MouseEvent e) {
      // TODO Auto-generated method stub
      JLabel label = (JLabel) e.getSource();
      label.setOpaque(false);
      label.setBackground(Color.WHITE);
    }      

當輕按兩下好友後 出現聊天框

@Override
    public void mouseClicked(MouseEvent e) {
      // TODO Auto-generated method stub
      // 如果輕按兩下了兩次 我的好友 彈出與這個好友的聊天框
      if (e.getClickCount() == 2) {
        JLabel label = (JLabel) e.getSource();
        new ChatUI(owner, label.getText(), client);
      }
    }      

一旦打開聊天框  就要建立一個線程  時刻監聽伺服器發送的消息

thread = new ClientThread(client, chat_txt);
    thread.start();      
//目前 對話框存在
    while (isOnline) {
      //I/O阻塞  接收服務端發送的資料
      CommandTranser msg = client.getData();
      if (msg != null) {
        /*
         * 如果服務端處理資料成功  接收資訊
         * 否則   彈出對方不線上的對話框
         */
        if (msg.isFlag()) {
          //發送時間
          Date date = new Date();
          SimpleDateFormat sdf = new SimpleDateFormat(
              "yy-MM-dd hh:mm:ss a");
          String message = msg.getSender() + "說:"
              + (String) msg.getData() + "\t" + sdf.format(date);
          // 在聊天框添加收到的資訊
          chat_txt.append(message+"\n");
        } else {
          JOptionPane.showMessageDialog(chat_txt, msg.getResult());
        }

      }
    }      

而當點選了對話框的發送按鈕時 将内容封裝為CommandTrander對象  用戶端向伺服器發送資料

// 如果點選了發送按鈕
    if (e.getSource() == send_btn) {
      Date date = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd hh:mm:ss a");

      String message = "你說:" + message_txt.getText() + "\t"
          + sdf.format(date);
      // 在本地文本區追加發送的資訊
      chat_txt.append(message+"\n");
      // msg為用戶端向伺服器發送的資料
      CommandTranser msg = new CommandTranser();
      msg.setCmd("message");
      msg.setSender(owner);
      msg.setReceiver(friend);
      msg.setData(message_txt.getText());

      client.sendData(msg);
      // 發送資訊完畢 寫資訊的文本框設空
      message_txt.setText(null);
    }      

好啦  代碼 就這麼多。聊天過程如下

繼續閱讀