Java中用网络通信实现聊天室私聊和群聊的功能

Java中用网络通信实现聊天室私聊和群聊的功能

客户端代码(Client):

package homework10.homework1015;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        //连接服务器
        try {
            System.out.println("连接服务端");
            Socket socket = new Socket("localhost",8088);
            System.out.println("连接服务端成功");
            Thread t1 = new Thread(new ClientWriteData(socket));
            Thread t2 = new Thread(new ClientReadData(socket));
            t1.start();
            t2.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class ClientWriteData implements Runnable{
    private Scanner scan;
    private Socket socket;
    public ClientWriteData(Socket socket){
        this.socket = socket;
    }
    public void run(){
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw;osw = new OutputStreamWriter(out,"GBK");
            PrintWriter pw = new PrintWriter(osw,true);
            System.out.println("请输入用户名:");
            scan = new Scanner(System.in);
            String str0 = scan.next();
            pw.println(str0);
            while(true){
                System.out.println("请选择私聊或者群发:1表示私聊\t2表示群发");
                int n = scan.nextInt();
                pw.println(n);
                switch(n){
                    case 1:
                        System.out.println("请输入私聊对象: ");
                        String name = scan.next();
                        pw.println(name);
                        System.out.println("私聊的信息:");
                        String str = scan.next();
                        pw.println(str);
                        break;
                    case 2:
                        System.out.println("请输入群发消息:");
                        System.out.println(str0+"正在发消息:");
                        String str1 = scan.next();
                        pw.println(str1);
                        break;
                    default:
                        System.out.println("退出消息发送:");
                        System.exit(0);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class ClientReadData implements Runnable{
    private Socket socket;
    public ClientReadData(Socket socket){
        this.socket = socket;
    }
    public void run(){
        try {
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is,"GBK");
            BufferedReader br = new BufferedReader(isr);
            String str = null;
            while((str = br.readLine())!=null){
                System.out.println(str);
            }
        } catch (IOException e) {
            System.err.println("服务端已断开!!!");
            e.printStackTrace();
        }
    }
}

服务端代码(Server):

package homework10.homework1015;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 要求实现谁和谁聊天的提示
 * @author Administrator
 *
 */
public class Server {
    //群发
    //定义一个集合,用于存储所有客户端的输出流
    List<PrintWriter> allPw = new ArrayList<>();
    //用于根据用户名存储客户端输出流
    Map<String,PrintWriter> map = new HashMap();
    //创建线程池对象
    //ExecutorService pool = Executors.newCachedThreadPool();
    public static void main(String[] args) {
        try {
            //向系统申请端口号 端口号是系统中所有程序没有使用过的端口,才能使用成功
            //端口号的范围:0-65535之间 0-1023之间是系统端口
            ServerSocket server = new ServerSocket(8088);
            System.out.println("服务端开启成功!!!");
            Server s = new Server();
            while(true){
                System.out.println("等待客户端连接:");
                //阻塞方法 accept():等待客户端的连接
                Socket accept = server.accept();
                System.out.println("和客户端连接成功!!!");
                //获取IP地址
                InetAddress address = accept.getInetAddress();
                String ip = address.getHostAddress();
                System.out.println(ip);
                Thread t = new Thread(s.new ClientHandler(accept));
                t.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    class ClientHandler implements Runnable{
        private Socket socket;
        public ClientHandler(Socket socket){
            this.socket = socket;
        }
        public void run(){
            try{
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,"GBK");
                BufferedReader br = new BufferedReader(isr);

                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os,"GBK");
                PrintWriter pw = new PrintWriter(osw,true);
                //一个客户端连接服务器,则把输出流存入到集合中
                String str = null;
                //用户名
                String name = br.readLine();
                allPw.add(pw);
                map.put(name, pw);
                while((str = br.readLine())!=null){
                    if(str.equals("1")){//私聊工作
                        //需要私聊的对象
                        str = br.readLine();
                        //私聊对象的输出流
                        PrintWriter p = map.get(str);
                        str = br.readLine();
                        p.println(str);
                    }else{//群发

                        System.out.println("");
                        str = br.readLine();
                        for(PrintWriter p:allPw){
                            if(p == pw){
                                continue;
                            }
                            p.println(str);
                        }
                    }
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

faramita_of_mine

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值