zoukankan      html  css  js  c++  java
  • java写一个简易聊天程序

    服务器端

    package com.cs;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;
    
    @SuppressWarnings("all")
    public class TCPServer {
        private static int port = 6077; //服务器端口
    
        public static void main(String[] args) throws IOException {
            ServerSocket server = new ServerSocket(port);
            Socket socket = server.accept();
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            Scanner sc = new Scanner(System.in);
            String msg = "";
            do {
                byte[] bytes = new byte[1024];
                int len = is.read(bytes);
                System.out.println("客户端:" + new String(bytes, 0, len));
                System.out.println("服务器端:");
                msg = sc.next();
                os.write(msg.getBytes());
            } while ((msg.equals("退出")) != true);
            socket.close();
            server.close();
    
        }
    }

    客户端

    package com.mvc.chat;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.util.Scanner;
    
    /**
     * 简易聊天小程序
     *
     * @author liuwenlong
     * @create 2021-04-17 10:25:39
     */
    @SuppressWarnings("all")
    public class TcpClient {
        private static String host = "这里写服务器的IP";//连接的服务器IP地址
        private static int port = 6077; //服务器端口
    
        public static void main(String[] args) throws IOException {
            Socket socket = new Socket(host, port); //创建Socket
            OutputStream os = socket.getOutputStream();
            InputStream is = socket.getInputStream();
            Scanner sc = new Scanner(System.in);
            String msg = "";
            do {
                System.out.println("客户端:");
                msg = sc.next(); //输入
                os.write(msg.getBytes());//写入到服务器
                byte[] bytes = new byte[1024];
                int len = is.read(bytes);
                System.out.println("服务器端:" + new String(bytes, 0, len));
            } while ((msg.equals("退出")) != true);
            socket.close();
        }
    }

    原创文章,转载请说明出处,谢谢合作
  • 相关阅读:
    mariadb 数据库集群配置
    mariadb 4
    mariadb 3
    mariadb 2
    mariadb 1
    firewalld 防火墙
    k8s集群搭建
    k8s控制器资源
    k8s Ingress和ingress控制器
    k8s service对象
  • 原文地址:https://www.cnblogs.com/lwl80/p/14669768.html
Copyright © 2011-2022 走看看