Socket

2021-09-09 11:33:24 浏览数 (2)

{tabs-pane label="服务端"}

代码语言:javascript复制
public class Demo804_1 {
    public static void main(String[] args)throws IOException {

        ServerSocket ss=new ServerSocket(520);//监听一个端口号
        System.out.println("监听服务开启");
        for (;;){
            Socket socket=ss.accept();//表示新用户来了就创建一个实例
            System.out.println("开启:" socket.getRemoteSocketAddress());
            Thread t=new hand(socket);
            t.start();
        }

    }
}
class hand extends Thread{
    Socket sock;
    public hand(Socket socket){
        this.sock=socket;
    }

    @Override
    public void run() {
        try(InputStream input=this.sock.getInputStream()){
            try(OutputStream outputStream=this.sock.getOutputStream()){
                handle(input,outputStream);
            }
        }catch (Exception e){
            try {
                this.sock.close();

            }catch (IOException ioe){
                System.out.println(ioe);
            }
            System.out.println("有问题了");
        }

    }
    private void handle(InputStream input,OutputStream out)throws IOException{
        var Writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
        var reader = new BufferedReader(new InputStreamReader(input,StandardCharsets.UTF_8));
        Writer.write("打开n");
        Writer.flush();
        for (;;){
            String s = reader.readLine();
            if (s.equals("y")){
                Writer.write("yn");
                Writer.flush();
                break;
            }
            Writer.write("游客:" s "n");
            Writer.flush();
        }
    }
}

{/tabs-pane} {tabs-pane label="客服端"}

代码语言:javascript复制
public class clinent {
    public static void main(String[] args)throws IOException {
        Socket sock=new Socket("localhost",520);
        try(InputStream input=sock.getInputStream()){
            try(OutputStream out=sock.getOutputStream()){
                handle(input,out);
            }
        }
    }
    private static void handle(InputStream inp,OutputStream out)throws IOException{
        var Writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
        var reader = new BufferedReader(new InputStreamReader(inp, StandardCharsets.UTF_8));
        Scanner s=new Scanner(System.in);
        System.out.println("开始监听:");
        for (;;){
            System.out.println("》》》");
            String s1 = s.nextLine();
            Writer.write(s1);
            Writer.newLine();
            Writer.flush();
            String s2 = reader.readLine();
            System.out.println("《《《" s2);
            if (s2.equals("y")){
                break;
            }
        }
    }
}

{/tabs-pane}

本文共 136 个字数,平均阅读时长 ≈ 1分钟

0 人点赞