JAVA+Socket 实现客户端键盘录入服务器写入文本

2020-09-23  本文已影响0人  清水_yuxin

1、服务端

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;


public class ServerDemo {
   public static void main(String[] args) throws IOException{
       ServerSocket ss = new ServerSocket(666);

       System.out.println("ServerSocket start...");

       // 监听客户端
       Socket s = ss.accept();

       System.out.println("server: Socket accept");
       // 封装通道内的数据
       BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

       // 封装文本文件.
       BufferedWriter bw = new BufferedWriter(new FileWriter("log.text"));

       String line = null;

       while ((line = br.readLine()) != null ) {
           System.out.println("server:"+line);
           bw.write(line);
           bw.newLine();
           bw.flush();
       }

       bw.close();
       s.close();
       System.out.println("server: Socket close");
   }
}

2、客户端

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class ClientDemo {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("127.0.0.1", 666);

        // 键盘录入
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // 封装通道数据
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

        String line = null;
        System.out.print("请输入内容:");
        while ((line = br.readLine()) != null) {
            if ("over".equals(line)) {
                System.out.println("client关闭键盘输入");
                break;
            }

            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        s.close();
        System.out.println("closed client Socket");
    }
}
上一篇下一篇

猜你喜欢

热点阅读