Contact me:

JAVA 无图形界面 双线程聊天程序

写在前面

之前的单线程版本没法自由输入和输出;用了多线程之后体验好了

代码

客户端

import java.io.*;
import java.net.*;

class CL {
    Socket cl;
    public CL(String ip) throws IOException {
        this.cl=new Socket(ip,9999);
        System.out.println("OK");
        BufferedReader in= new BufferedReader(new InputStreamReader(cl.getInputStream()));
        BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
        PrintStream ot=new PrintStream(cl.getOutputStream(),true);
        ot.println("connected");

        Thread readThread=new Thread(()-> {while (true) {
            System.out.print("Server:");
            String sv = null;
            try {
                sv = in.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(sv);}});

        Thread wtThread=new Thread(()-> {while (true) {
            System.out.println("Message:");
            String msg = null;
            try {
                msg = rd.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ot.println(msg);
        }});
        readThread.start();
        wtThread.start();
    }
    public static void main(String[] args) throws IOException {
        System.out.println("enter your dest-ip:");
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String ip= br.readLine();
        CL CL=new CL(ip);
    }
}

服务端

import java.io.*;
import java.net.*;
class SERV {
    Socket cl;
    ServerSocket ser;

     SERV() throws IOException {
        this.ser = new ServerSocket(9999);
        InetAddress inetAddr = InetAddress.getLocalHost();
        System.out.println("Connecting,LocalIP:"+ inetAddr.getHostAddress());
        this.cl = ser.accept();
        //System.out.println("Connected");
        PrintStream ot=new PrintStream(cl.getOutputStream());
        BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
        BufferedReader in= new BufferedReader(new InputStreamReader(cl.getInputStream()));
        ot.println("plz");

        Thread readThread=new Thread(()-> {while (true) {
            System.out.print("Client:");
            String sv = null;
            try {
                sv = in.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(sv);}});

        Thread wtThread=new Thread(()-> {while (true) {
            System.out.println("Message:");
            String msg = null;
            try {
                msg = rd.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ot.println(msg);
        }});
        readThread.start();
        wtThread.start();

    }
    public static void main(String[] args) throws IOException {
        SERV SERV=new SERV();

    }
}
posted @ 2021-10-27 23:48  impwa  阅读(68)  评论(0编辑  收藏  举报