TCP实现的客户端键盘输入数据存储到服务器端文件中
程序员文章站
2022-07-01 08:02:54
...
包装输出流,这样就可以一行一行的读取;
输入流关联键盘输入,就不用创建Scanner类,再进行录入了;
客户端:
import java.io.*;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket sk = new Socket("192.168.10.103",6666);
OutputStream out = sk.getOutputStream();
//包装输出流;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line =null;
System.out.println("请输入发送的消息:");
while ((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
if (line.equals("bye")){
break;
}
}
sk.close();
}
}
服务端:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6666);
System.out.println("服务器正常开启!");
//侦听客户端,连接传入之前处于阻塞状态;
Socket sk = ss.accept();
InputStream in = sk.getInputStream();
//包装输入流;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedWriter bw = new BufferedWriter(new FileWriter("Msg.txt"));
String line=null;
while ((line=br.readLine())!=null){
System.out.println("来消息了:"+line);
bw.write(line);
bw.newLine();
bw.flush();
if (line.equals("bye")){
break;
}
}
ss.close();
}
}