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

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

作者: 清水_yuxin | 来源:发表于2020-09-23 23:06 被阅读0次

    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");
        }
    }
    

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/fryayktx.html