• 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();
        }
    }

    原创文章,转载请说明出处,谢谢合作
  • 相关阅读:
    Pentaho
    sympy 解四元一次方程
    install R language on ubuntu
    pyside
    浙江省医院网上挂号
    mtu值相关
    Python 中除法运算需要注意的几点
    idea
    kilim
    good blog
  • 原文地址:https://www.cnblogs.com/lwl80/p/14669768.html
Copyright © 2020-2023  润新知