App下載

Java實現(xiàn)多人聊天室的原理 具體源碼實現(xiàn)

猿友 2021-07-15 11:27:28 瀏覽數(shù) (3560)
反饋

我們在日常交際中,會使用QQ或者微信拉一些個有共同語言的朋友建立群聊?,F(xiàn)在,學(xué)習(xí)了Java語言,嘗試著用Java做一個自己的聊天室。接下來我將會為你介紹多人聊天室的原理,以及怎么用Java代碼實現(xiàn)多人聊天室。詳情內(nèi)容如下。

多人聊天室原理圖

多人聊天室原理圖

源碼

工具類:

該類用于關(guān)閉各種流。

public class CloseUtil {
 public static void CloseAll(Closeable... closeable){
  for(Closeable c:closeable){
   if (c != null) {
    try {
     c.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

服務(wù)器:

服務(wù)器端創(chuàng)建一個serverSocket對象通過accept()方法監(jiān)聽是否有tcp連接,同時有一個儲存socket對象的集合將連接進來的對象儲存到List集合中,服務(wù)器將消息進行轉(zhuǎn)發(fā)。

//服務(wù)器
public class Server {
 //存儲每一個連接進來的客戶端
 public static List<MyChannel> list=new ArrayList<>();

 public static void main(String[] args) throws Exception {
   //創(chuàng)建ServerSocket對象
  ServerSocket serverSocket = new ServerSocket(9999);
  while (true){
   //連接進來的客戶端
   Socket client = serverSocket.accept();
   System.out.println(client.getInetAddress()+"進入聊天室");
  MyChannel myChannel = new MyChannel(client);
  list.add(myChannel);
  new Thread(myChannel).start();
  }
 }
}

消息轉(zhuǎn)發(fā)類:

具體的消息轉(zhuǎn)發(fā)實現(xiàn)類,將信息發(fā)給除發(fā)送消息以外的其他客戶端。

//用于信息轉(zhuǎn)發(fā)
public class MyChannel implements Runnable{
 private DataInputStream dis;
 private DataOutputStream dos;
 private boolean flag=true;

 public MyChannel(Socket socket) {
  try{
   dis=new DataInputStream(socket.getInputStream());
   dos=new DataOutputStream(socket.getOutputStream());
  }catch (IOException e){
   flag=false;
   CloseUtil.CloseAll(dis,dos);
  }
 }
 //接收數(shù)據(jù)的方法
 private String receive(){
  String str="";
  try{
   str= dis.readUTF();
  }catch (IOException e){
   flag=false;
   CloseUtil.CloseAll(dis,dos);
   Server.list.remove(this);
  }
  return str;
 }
 //發(fā)送數(shù)據(jù)的方法
 private void send(String str){
  try {
   if (str != null && str.length() != 0) {
    dos.writeUTF(str);
    dos.flush();
   }
  }catch (Exception exception){
   flag=false;
   CloseUtil.CloseAll(dos,dis);
   Server.list.remove(this);
  }
 }
 //轉(zhuǎn)發(fā)消息的方法
 private void sendToOther(){
  String str=this.receive();
  List<MyChannel> list = Server.list;
  for (MyChannel other:list) {
   if(other==list){
    continue;//不發(fā)送信息給自己
   }
   //將消息發(fā)送給其他客戶端
   other.send(str);
  }
 }

 @Override
 public void run() {
  while (flag){
   sendToOther();
  }
 }
}

發(fā)送信息類:

用于從鍵盤上獲取數(shù)據(jù)然后將數(shù)據(jù)發(fā)送出去

public class Send implements Runnable{
 //從鍵盤上獲取數(shù)據(jù)
 private BufferedReader br;
 private DataOutputStream dos;
 private boolean flag=true;

 public Send() {
  br=new BufferedReader(new InputStreamReader(System.in));
 }
 public Send(Socket socket){
  this();
  try{
   dos=new DataOutputStream(socket.getOutputStream());
  }catch (Exception e){
   flag=false;
   CloseUtil.CloseAll(dos,socket);
   e.printStackTrace();
  }
 }


 private String getMessage(){
  String str="";
  try{
   str=br.readLine();
  }catch (IOException e){
   flag=false;
   CloseUtil.CloseAll(br);
  }
  return str;
 }
 private void send(String str){
  try {
   dos.writeUTF(str);
   dos.flush();
  } catch (IOException e) {
   flag=false;
   CloseUtil.CloseAll(dos);
   e.printStackTrace();
  }

 }

 @Override
 public void run() {
  while (flag){
   this.send(getMessage());
  }
 }
}

信息接收類:

public class Receive implements Runnable{
  //接受數(shù)據(jù)流
  private DataInputStream dis;
  private boolean flag=true;


  public Receive(Socket socket){
    try {
      dis = new DataInputStream(socket.getInputStream());
    }catch (Exception e){
      flag=false;
      CloseUtil.CloseAll(dis,socket);
    }
  }
  private String getMessage(){
    String str="";
    try {
      str=dis.readUTF();
    } catch (IOException e) {
      flag=false;
      CloseUtil.CloseAll(dis);
      e.printStackTrace();
    }
    return str;
  }
  @Override
  public void run() {
    while (flag){
      System.out.println(this.getMessage());
    }
  }
}

客戶端:

public class client {
  public static void main(String[] args) throws Exception{
    Socket socket = new Socket(InetAddress.getLocalHost(),9999);
    Send send = new Send(socket);
    Receive receive = new Receive(socket);
    new Thread(send).start();
    new Thread(receive).start();
  }
}

先將服務(wù)器啟動然后啟動客戶端:測試結(jié)果如下

測試結(jié)果

有喜歡的小伙伴可以自己拿去玩,代碼復(fù)制直接有效。

總結(jié)

本篇文章關(guān)于使用Java代碼實現(xiàn)多人聊天室的內(nèi)容就到此結(jié)束,更多相關(guān)Java有趣的內(nèi)容請搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章l


1 人點贊