Java编写实现多人聊天室

2023-05-16 0 1,566

本文实例大家分享Java实现多人聊天室的具体代码,供大家参考,具体内容如下

1.客户端

package tk.javazhangwei.net.tcp.chat.Demo03;
 
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
 
/***
 * 创建客户端  发送数据+接收数据
 * 
 * @author zw
 *
 */
public class Client {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        System.out.println(\"请输入一个喜欢的名称:\");
        String name = bf.readLine();
        if(name.equals(\"\")) {
            return;
        }
        
        Socket client = new Socket(\"localhost\",1025);
        //控制台输入信息
        //控制台输入信息
        new Thread(new Send(client,name)).start();//一条路径
        new Thread(new Receive(client)).start();//一条路径
}
}

2.服务端(写了个内部类:负责接收与发送多进程)

package tk.javazhangwei.net.tcp.chat.Demo03;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
 
public class Server {
    List<myChannel> all = new ArrayList<myChannel>();
    
    
    
    public static void main(String[] args) throws IOException {
        new Server().start();
        
 
    }
    
    
    public void start() throws IOException {
        ServerSocket server = new ServerSocket(1025);
        while (true) {
            Socket socket = server.accept();
            myChannel mc = new myChannel(socket);
            Thread t = new Thread(mc);
            all.add(mc);
            t.start();
    }
}
 
 
/***
 * 一个客户端 一个通路
 * @author zw
 *
 */
class myChannel implements Runnable{
    private DataInputStream dis;
    private DataOutputStream dos;
    private boolean isRuning=true;
    private String name;
    
    public myChannel(Socket socket) throws IOException{
        try {
            dis = new DataInputStream(socket.getInputStream());
            dos = new DataOutputStream(socket.getOutputStream());
            this.name = dis.readUTF();
            send(\"欢迎进入聊天室\");
            senOthers(this.name + \"进入了聊天室\");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
                isRuning=false;
                dos.close();
                dis.close();
                
        }
        
    }
    /***
     * 读取数据
     * 
     * @return
     * @throws IOException
     */
    private String receive() throws IOException {
        String msg =\"\";
        try {
            msg =dis.readUTF();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            isRuning=false;
            dis.close();
        
        }
        
        
        return msg;    
    }
    /***
     * 发送数据
     * @throws IOException 
     */
    private void send(String msg) throws IOException {
        if(msg==null&& msg.equals(\"\")) {
            return;
        }
        try {
            dos.writeUTF(msg);
            dos.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            isRuning=false;
            dos.close();
            all.remove(this);
        }
        
    }
    /***
     * 发送给其他客户端
     * @throws IOException 
     */
    private void senOthers(String msg) throws IOException {
        if (msg.startsWith(\"@\")&&msg.indexOf(\":\")>-1) {// 表示为私聊
            //获取name
            String name = msg.substring(1, msg.indexOf(\":\"));
            String content = msg.substring(msg.indexOf(\":\")+1);//获取冒号后的正文
            for (myChannel others : all) {
                if(others.name.equals(name)) {
                    others.send(this.name+\"对您瞧瞧的说:\"+content);
                }
                
            }
            
            
        } else {
        //遍历容器
        for(myChannel others:all) {
            if(others == this) {//如果是本身,就跳过
                continue;
            }
            others.send(this.name+\"对所有人说:\"+msg);
        }
        }
    }
    
    @Override
    public void run() {
        while(isRuning) {
            try {
                senOthers(receive()) ;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        }
}
}

3.客户端的发送与接收多进程

package tk.javazhangwei.net.tcp.chat.Demo03;
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
 
/***
 * 发送数据
 * 
 * @author zw
 *
 */
public class Send implements Runnable{
    //控制台输入流
    private BufferedReader console;
    //管道输出流
    private DataOutputStream dos;
    private String name;
    
    private boolean isRuning =true;//线程是否运行
    
    public Send() {
        console =new BufferedReader(new InputStreamReader(System.in));
    }
    
    public Send(Socket client,String name) throws IOException {
        this();
        try {
            dos = new DataOutputStream(client.getOutputStream());
            this.name = name;
            send(name);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
             isRuning =false;
             dos.close();
             console.close();
        }
    }
    private String getMsgFromConsole() {
        try {
            return console.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return \"\";
    }
 
    
@Override
    public void run() {
        
        while(isRuning) {
            try {
                send(getMsgFromConsole());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

 
    public void send(String msg) throws IOException {
        if (msg!=null && !msg.equals(\"\")) {
            try {
                dos.writeUTF(msg);
                dos.flush();// 强制刷新
            } catch (IOException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
                isRuning = false;
                dos.close();
                console.close();
 
            }
        }
    }
 
}
package tk.javazhangwei.net.tcp.chat.Demo03;
 
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
 
/***
 * 接收数据
 * @author zw
 *
 */
public class Receive implements Runnable{
    //客户端的输入流
    private DataInputStream dis;
    private boolean isRuning = true;
    
    public Receive() {
    
    }
 
    public Receive(Socket client) {
        super();
        try {
            dis = new DataInputStream(client.getInputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            isRuning =false;
            try {
                dis.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }
    /***
     * 接收数据
     * @return
     * @throws IOException 
     */
    public String receive() throws IOException {
        String msg = \"\";
        try {
            msg =dis.readUTF();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            isRuning =false;
            dis.close();
        }
        
        return msg;
    }
    @Override
    public void run() {
        while(isRuning) {
            try {
                System.out.println(receive());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
 
}

4.效果

Java编写实现多人聊天室

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

资源下载此资源下载价格为1小猪币,终身VIP免费,请先
由于本站资源来源于互联网,以研究交流为目的,所有仅供大家参考、学习,不存在任何商业目的与商业用途,如资源存在BUG以及其他任何问题,请自行解决,本站不提供技术服务! 由于资源为虚拟可复制性,下载后不予退积分和退款,谢谢您的支持!如遇到失效或错误的下载链接请联系客服QQ:442469558

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 Java编写实现多人聊天室 http://www.20zxx.cn/705204/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务