网络编程_客户端键盘录入服务器写到文本文件
原创
©著作权归作者所有:来自51CTO博客作者wx62dfdc6aea345的原创作品,请联系作者获取转载授权,否则将追究法律责任
package cn.itcast_09;
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 {
// 创建服务器端Socket对象
ServerSocket ss = new ServerSocket(15669);
// 监听客户端
Socket s = ss.accept();
// 获取输出流,输出到文本文件中
BufferedReader br = new BufferedReader(new InputStreamReader(
s.getInputStream()));
// 输入到文本文件
BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
// 释放资源
bw.close();
s.close();
}
}
package cn.itcast_09;
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对象
Socket s = new Socket("192.168.31.165", 15669);
// 键盘录入数据
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 封装通道流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
String line = null;
while ((line = br.readLine()) != null) {
// 自定义键盘录入结束标记
if ("886".equals(line)) {
break;
}
bw.write(line);
bw.newLine();
bw.flush();
}
// 释放资源
s.close();
}
}