溫馨提示×

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

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

java怎么實(shí)現(xiàn)群聊功能

發(fā)布時(shí)間:2022-05-19 16:46:19 來(lái)源:億速云 閱讀:235 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹“java怎么實(shí)現(xiàn)群聊功能”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“java怎么實(shí)現(xiàn)群聊功能”文章能幫助大家解決問(wèn)題。

1、服務(wù)端

package networkCoding;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CopyOnWriteArrayList;
 
/**
 * 
 * 1, 指定端口,使用serverSocket創(chuàng)建服務(wù)器
 * 2, 阻塞式等待連接accept
 * 3, 操作:輸入輸出流操作
 * 4, 釋放資源
 * 
 * 5,加入容器實(shí)現(xiàn)群聊
 * 
 * **/
 
public class WeiHuShanChatRoomServer {
    private static CopyOnWriteArrayList<Chat> all= new CopyOnWriteArrayList<Chat>();
 
    public static void main(String[] args) throws IOException {
        System.out.println("-----server");
         // 1, 指定端口,使用serverSocket創(chuàng)建服務(wù)器
        ServerSocket server= new ServerSocket(9999);
         // 2, 阻塞式等待連接accept
        while(true) {
        Socket client=server.accept();
        Chat chat= new Chat(client);
        // 交給容器管理
        all.add(chat);
        new Thread(chat) .start();
        }
    }
    static class Chat implements Runnable{
        private DataOutputStream dos;
        private DataInputStream dis;
        private Socket client;
        private boolean isRuning;
        private String name;
        public Chat(Socket client) {
            this.client=client;
            this.isRuning=true;
            try {
                this.dis = new DataInputStream(client.getInputStream());
                this.dos=new DataOutputStream(client.getOutputStream());
                this.name=receive();
                this.send(this.name+",威虎山歡迎你的到來(lái)");
                this.sendOthers(this.name+"來(lái)到了威虎山",true);
            } catch (IOException e) {
                // 出錯(cuò)釋放資源
                System.out.println("===1==");
                this.release();
            
            }
        }
        private String receive() {
            String data="";
            try {
                data= dis.readUTF();
            } catch (IOException e) {
                System.out.println("===2==");
                //this.release();
                
            }
            return data;
        }
        // 群聊
        private void send(String data) {
            try {
                dos.writeUTF(data);
                dos.flush();
            } catch (IOException e) {
                System.out.println("===3==");
                this.release();
                
            }
        }
        private void sendOthers(String data,boolean isSys) {
            boolean isPrivate = data.startsWith("@"); 
            if(isPrivate) {
                int index= data.indexOf(":");
                String targetName=data.substring(1,index);
                String msg=data.substring(index+1);
                for (Chat chat : all) {
                    if(chat.name.equals(targetName)) {
                        System.out.println("******"+chat.name+targetName);
                        chat.send(this.name+"悄悄對(duì)你說(shuō):"+msg);
                    }
                }
                
            }else {
                for (Chat chat : all) {
                    if(chat==this) {
                        continue;
                    }else {
                        if(isSys) {
                            chat.send(data);
                        }else {
                            chat.send(this.name+"對(duì)大家說(shuō):"+data);
                        }
                    }
                    
                }
            }
            
        }
        private void release() {
            this.isRuning=false;
            Utils.close(dis,dos,client);
            all.remove(this);
            sendOthers(this.name+"離開(kāi)了威虎山", true);
        }
        @Override
        public void run() {
            while(isRuning) {
                String data = receive();
                if(!data.equals("")) {
                     sendOthers(data,false);
                }else {
                    send("不能發(fā)送空消息");
                }
                
            }
            
        }
    }
 
}

2、客戶(hù)端

package networkCoding;
 
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
 
/**
 * 
 * 1, 建立連接,使用socket 創(chuàng)建客戶(hù)端 + 服務(wù)端的地址端口號(hào);
 * 2, 操作:輸入輸出流操作
 * 3, 釋放資源
 * 
 * **/
 
public class WeiHuShanChatRoomClient {
 
    public static void main(String[] args) throws UnknownHostException, IOException {
        BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
        System.out.println("請(qǐng)輸入姓名");
        String bfString = bf.readLine();
        //1, 建立連接,使用socket 創(chuàng)建客戶(hù)端 + 服務(wù)端的地址端口號(hào);
        Socket client = new Socket("localhost",9999);
        // 2, 操作:輸入輸出流操作
        new Thread(new Send(client,bfString)).start();
        new Thread(new Receive(client)).start();
        
    }
    
 
}

(1)發(fā)送封裝類(lèi)

package networkCoding;
 
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
 
public class Send implements  Runnable{
    private BufferedReader bf;
    private DataOutputStream dos;
    private Socket client;
    private boolean isRuning;
    private String name;
    public Send(Socket client,String name) {
        this.client=client;
        this.isRuning=true;
        this.name=name;
        this.bf= new BufferedReader(new InputStreamReader(System.in));
        try {
            this.dos=new DataOutputStream(client.getOutputStream());
            this.send(name);
        } catch (IOException e) {
            // 出錯(cuò)釋放資源
            System.out.println("===4==");
            this.release();
            this.isRuning=false;
        }
    }
    private void release() {
        this.isRuning=false;
        Utils.close(dos,client);
    }
    private void send(String data) {
        try {
            dos.writeUTF(data);
            dos.flush();
        } catch (IOException e) {
            System.out.println("===5==");
            this.release();
            
        }
    }
    private String getString() {
        String dataString ="";
        try {
            dataString = this.bf.readLine();
        } catch (IOException e) {
            System.out.println("===6==");
            this.release();
        }
        return dataString;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(isRuning) {
            String data = getString();
            if(!data.equals("")) {
                send(data);
            }else {
                //send("不能發(fā)送空消息");
            }
            
        }
    }
 
}

(2)接收封裝類(lèi)

package networkCoding;
 
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
 
public class Receive implements Runnable {
    private DataInputStream dis;
    private Socket client;
    private boolean isRuning;
    public Receive(Socket client) {
        this.client=client;
        this.isRuning=true;
        try {
            this.dis = new DataInputStream(client.getInputStream());
        } catch (IOException e) {
            // 出錯(cuò)釋放資源
            System.out.println("===6==");
            this.release();
            this.isRuning=false;
        }
    }
    private String receive() {
        String data="";
        try {
            data= dis.readUTF();
        } catch (IOException e) {
            System.out.println("===7==");
            this.release();
        }
        return data;
    }
    private void release() {
        this.isRuning=false;
        Utils.close(dis,client);
    }
    @Override
    public void run() {
        while(isRuning) {
            String data = receive();
            if(!data.equals("")) {
                System.out.println(data);
            }else {
                
            }
            
        }
        
    }
 
    
 
}

3、工具類(lèi)

package networkCoding;
 
import java.io.Closeable;
import java.io.IOException;
 
public class Utils {
    public static void main(String[] args) {
        
    }
    public static void close(Closeable...target) {
        for (Closeable obj : target) {
            try {
                if(null!=obj) {
                    obj.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

關(guān)于“java怎么實(shí)現(xiàn)群聊功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

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

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

AI