java实现简单的聊天室

这篇博客介绍了一个使用Java实现的两台电脑间进行信息交换的简单应用。通过ServerSocket和Socket实现网络通信,多线程处理接收和发送消息,使得两个客户端可以互相发送文本信息。启动顺序为先启动服务器,再启动客户端。代码中,服务器端负责监听和处理客户端连接,客户端则调用服务器的方法进行交互。
摘要由CSDN通过智能技术生成

这次的功能就是两台电脑之间可以实现对骂

那就直接上手了。
需要用到多线程和网络编程

1. Server

public class Server6666 {
    public static void main(String[] args) throws IOException {
        System.out.println("server is runing ....");
        //开启一个端口为6666的服务
        ServerSocket ss = new ServerSocket(6666);
        Scanner sc = new Scanner(System.in);
        //获取客户端
        Socket c = ss.accept();
        sendMsg(sc, c);
        acceptMsg(c);
    }

	//接受消息并且打印消息的方法
    public static void acceptMsg(Socket c) {
        new Thread(()->{
            try {
                InputStream inputStream = c.getInputStream();
                DataInputStream dii = new DataInputStream(inputStream);
                while (true){
                    System.out.println(c.getRemoteSocketAddress()+":"+dii.readUTF());
                }

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

        }).start();
    }

	//发送消息的方法
    public static void sendMsg(Scanner sc, Socket c) {
        new Thread(()-> {
            try {
                OutputStream outputStream = c.getOutputStream();
                DataOutputStream dis = new DataOutputStream(outputStream);
                while (true) {
                    dis.writeUTF(sc.next());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }).start();
    }
}

然后就是客户端

2. Client

    public static void main(String[] args) throws IOException {
        System.out.println("client is runing...");
        Socket c = new Socket("localhost", 6666);
        Scanner sc = new Scanner(System.in);

        Server6666.sendMsg(sc, c);
        Server6666.acceptMsg(c);

    }

注意: 启动顺序是先启动server然后再启动客户端

你可能注意到了为啥客户端的代码为啥这么少啊,主要是我这里把方法都封装到了Server中。所以代码才少

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值