Java中tcp实现双人聊天

客户端:

public class SocketClient {
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        Socket client = new Socket("localhost", 6666);
        while (true) {
           OutputStream out = client.getOutputStream();
           //从控制台输入
           System.out.println("客户端发送数据");
           String str = input.next();
           out.write(str.getBytes());
          //  System.out.println("信息发送成功"+str);
           if (str.equals("over")) {
               System.out.println("客户端已关闭");
               out.close();
               client.close();
               break;
           }
           //-------------------客户器端读取回复信息----------------------//
           InputStream in = client.getInputStream();
           //4.读取数据
           byte[] b = new byte[1024];
           int len = in.read(b);
           //接收到的数据
           String info = new String(b, 0, len);
           System.out.println("这是从客户端接收的数据:" + info);
       }
    }
}

服务器端:

public class SocketServer {
    public static void main(String[] args) throws Exception {
            System.out.println("服务器端启动,等待连接--------------");
            //1.创建ServerSocket对象,绑定端口,开始等待连接
            ServerSocket ss = new ServerSocket(6666);
            //2.接受连接,accept方法,返回Socket对象
            Socket server = ss.accept();
        while (true) {
            //3.通过Socket获取输入流
            InputStream in = server.getInputStream();
            //4.读取数据
            byte[] b = new byte[1024];
            int len = in.read(b);
            //接收到的数据
            String info = new String(b, 0, len);
            System.out.println("这是从客户端接收的数据:" + info);

            if (info.equals("over")) {

                System.out.println("服务器已关闭");
                in.close();
                server.close();
                break;
            }
//-------------------服务器端回复信息----------------------//
            System.out.println("服务器回复客户端信息:");
            OutputStream out = server.getOutputStream();
            //从控制台输入
            Scanner input = new Scanner(System.in);
            String str = input.next();
            out.write(str.getBytes());

        }
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值