用BufferWrite实现让数据在客户端和服务器端进行传输。发现只有在使用write方法时加上换行符,数据才能在服务器端输出,否则就输出不了。这是为什么啊?BufferWrite必须有换行符才能写入数据吗?
以下是代码:
// 客户端
public class ProducerStarter_V3 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 9090);
OutputStream outputStream = socket.getOutputStream();
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(outputStream));
Properties properties = new Properties();
properties.load(new FileReader(".\\conf\\producer.properties"));
String datasourceClassname = properties.getProperty("datasource_classname");
String datasourceConstructorParam = properties.getProperty("datasource_constructor_param");
Class<?> aClass = Class.forName(datasourceClassname);
Constructor<?> constructor = aClass.getConstructor(String.class);
Iterator<String> dataSourceIter = (Iterator<String>) constructor.newInstance(datasourceConstructorParam);
while (dataSourceIter.hasNext()) {
String next = dataSourceIter.next();
// 不太明白的位置
br.write(next + "\n");
br.flush();
}
}
}
// 服务器端
public class EngineStarter {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9090);
Socket accept = serverSocket.accept();
// 接收数据
InputStream inputStream = accept.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while (true) {
String s = br.readLine();
System.out.println(s);
}
}
}