利用java实现简单的tcp通信
要求:
客户端:数据来自于键盘的录入,直到输入的数据为:结束,发送数据结束
服务器:接收数据,并将数据写入到文件中去
client
package tcp;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class client01 {
public static void main(String[] args) throws IOException {
Socket s = new Socket("10.133.162.170",10003);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line;
while ((line = br.readLine())!=null){
if ("结束".equals(line)){
break;
}
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
s.close();
}
}
服务器
package tcp;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class server001 {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10003);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bw = new BufferedWriter(new FileWriter("exe\\tt.txt"));
String line;
while ((line = br.readLine())!=null){
System.out.println(line);
bw.write(line);
bw.newLine();
bw.flush();
}
ss.close();
}
}