溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用socket實(shí)現(xiàn)網(wǎng)絡(luò)聊天室和私聊功能

發(fā)布時(shí)間:2020-09-01 17:29:04 來源:腳本之家 閱讀:392 作者:jike_chengwei 欄目:編程語言

使用socket技術(shù)實(shí)現(xiàn)網(wǎng)絡(luò)聊天室和私聊功能,具體內(nèi)容如下

話不多說先上圖:

1、聊天室群聊頁面

使用socket實(shí)現(xiàn)網(wǎng)絡(luò)聊天室和私聊功能

在線用戶的聯(lián)系人列表

使用socket實(shí)現(xiàn)網(wǎng)絡(luò)聊天室和私聊功能

socket連接頁面

使用socket實(shí)現(xiàn)網(wǎng)絡(luò)聊天室和私聊功能

私聊頁面

使用socket實(shí)現(xiàn)網(wǎng)絡(luò)聊天室和私聊功能

項(xiàng)目介紹

與服務(wù)端實(shí)現(xiàn)socket連接:每個(gè)客戶端連接到服務(wù)器的時(shí)候,服務(wù)器會(huì)將每個(gè)連接的socket保存在list集合中。

群聊功能:當(dāng)有一個(gè)用戶發(fā)送群聊消息給服務(wù)器的時(shí)候,服務(wù)器會(huì)將所有信息轉(zhuǎn)發(fā)給list列表中的所有已連接的客戶端。

私聊功能:用戶發(fā)送私聊信息給服務(wù)器后,服務(wù)器會(huì)向一個(gè)目標(biāo)ip發(fā)送消息。

顯示在線聯(lián)系人列表:當(dāng)有新用戶登錄成功的時(shí)候,服務(wù)器會(huì)將在線聯(lián)系人的信息用json字符串的形式發(fā)送給客戶端,客戶端通過解析json字符串來獲取在線聯(lián)系人的信息。

自定義一個(gè)強(qiáng)大的類SocketEvent:客戶端與服務(wù)器通信全部都是通過這個(gè)類來保存數(shù)據(jù)的,然后使用fastjson工具來把類對象轉(zhuǎn)換為json字符串來傳輸。

public class SocketEvent {

  private int type =0;

  private String msg ="";

  private String keyIP =""; // 關(guān)鍵IP

  private String temporaryIP =""; // 臨時(shí)IP

  public SocketEvent() {
  }

  public int getType() {
    return type;
  }

  public void setType(int type) {
    this.type = type;
  }

  public String getMsg() {
    return msg;
  }

  public void setMsg(String msg) {
    this.msg = msg;
  }

  public String getKeyIP() {
    return keyIP;
  }

  public void setKeyIP(String keyIP) {
    this.keyIP = keyIP;
  }

  public String getTemporaryIP() {
    return temporaryIP;
  }

  public void setTemporaryIP(String temporaryIP) {
    this.temporaryIP = temporaryIP;
  }
}

type: 標(biāo)志當(dāng)前發(fā)送的信息是什么類型的信息。服務(wù)端和客戶端解 析數(shù)據(jù)就是通過這個(gè)它來判斷屬于哪種類型的消息

public static final int CHAT_PRIVATE = 111; // 私聊的指令
  public static final int CHAT_GROUP = 222; // 群聊的指令
  public static final int SOCKET_SUCCESS = 333; // socket連接成功的指令
  public static final int SOCKET_FAIL = 444; // socket連接失敗的指令
  public static final int CONNECT_SUCCESS = 666; // socket連接成功的指令
  public static final int CONNECT_FAIL = 777; // socket連接失敗的指令
  public static final int LOGIN_ARG = 888; // socket接收到標(biāo)志新用戶登錄的指令
  public static final int CANCEL_ARG = 999; // socket接收到標(biāo)志用戶注銷的指令
  public static final int NEW_CLIENT = 3332; // 新用戶登錄的指令
  public static final int ALL_CLIENT = 3432; // 新用戶登錄后接收到所有在線用戶的指令
  public static final int SEND_PRIVATE = 5666; // 發(fā)送私聊消息的指令
  public static final int SEND_IPlIST = 6666; // 發(fā)送已登錄的用戶IP集合的指令


keyIP:客戶端消息發(fā)起者的ip地址

temperoryIP:臨時(shí)的IP地址,如果是type是私聊類型的那么這個(gè)ip代表的就是目標(biāo)聯(lián)系人的ip地址

服務(wù)端代碼 (ServerSocket)

1. 接收客戶端的連接

Socket Socketclient = server.accept();

2.開啟線程實(shí)時(shí)接收來自客戶端的信息

// 實(shí)時(shí)獲取客戶端發(fā)送的數(shù)據(jù)
    @Override
    public void run() {
      try {
        while (true) {
          if ((acceptLine = in.readLine()) != null) {
            System.out.println("<接收到的消息是>" + acceptLine);

            SocketEvent event = JSON.parseObject(acceptLine, SocketEvent.class);

            switch (event.getType()) {
            case UtilFactory.CHAT_GROUP:
              sendMsgAvoid(event.getKeyIP(), acceptLine);
              break;

            case UtilFactory.SEND_PRIVATE:
              event.setType(UtilFactory.CHAT_PRIVATE);
              sendMsgTarget(event.getTemporaryIP(), JSON.toJSONString(event));

              break;
            }

          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }


3. 向指定ip發(fā)送消息的方法和除了自己ip向其他所有ip發(fā)送消息的方法

// 向指定的ip地址發(fā)送消息
    private void sendMsgTarget(String targetIP, String msg) {
      int num = mList.size();

      for (int index = 0; index < num; index++) {
        Socket mSocket = mList.get(index);

        String ip = mSocket.getInetAddress().getHostAddress();

        if (ip.equals(targetIP)) {
          PrintWriter pout = null;
          try {
            pout = new PrintWriter(
                new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8")), true);
            pout.println(msg);

            // 退出方法
            return;
          } catch (IOException e) {
            e.printStackTrace();
          }
        }

      }
    }

    // 向除了這個(gè)ip以外的所有ip發(fā)送
    private void sendMsgAvoid(String avoidIP, String msString) {

      int num = mList.size();

      for (int index = 0; index < num; index++) {
        Socket mSocket = mList.get(index);

        String ip = mSocket.getInetAddress().getHostAddress();

        if (!ip.equals(avoidIP)) {
          PrintWriter pout = null;
          try {
            pout = new PrintWriter(
                new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8")), true);
            pout.println(msString);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }

      }
    }

客戶端在mainActivity中接受來自服務(wù)端的所有信息,根據(jù)type來進(jìn)行再次分裝,使用Eventbus將信息發(fā)送給各個(gè)fragment來進(jìn)行展示

@Subscribe(threadMode = ThreadMode.MAIN)
  public void privateChat(SocketEvent event) {
    switch (event.getType()) {
      case MyApplication.CHAT_PRIVATE:
        // 將消息post給私聊聊天室
        ChatMessageBean bean = new ChatMessageBean();
        bean.setMsg(event.getMsg());
        bean.setName(event.getKeyIP());
        bean.setType(ChatMessageBean.OTHERS_ARG);
        EventBus.getDefault().post(bean);
        break;

      case MyApplication.SEND_PRIVATE:
        sendMsg(JSON.toJSONString(event));
        break;
    }
  }

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI