本帖最后由 舒远 于 2012-9-11 19:53 编辑
- public class SocketClient {
- public static void main(String[] args) throws Exception {
- Socket socket = new Socket("localhost", 11000);
- PrintWriter writer = new PrintWriter(socket.getOutputStream());
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- BufferedReader readerIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- String line = null;
- while ((line = reader.readLine()) != null) {
- if (line.equals("over"))
- break;
- writer.println(line);
- //writer.flush();//如果这里被注释掉则无法收到服务端返回的消息
-
- String line1 = readerIn.readLine();
- System.out.println(line1);
- }
- reader.close();
- writer.close();
- socket.close();
- }
- }
- public class SocketServer {
- public static void main(String[] args) throws Exception {
- ServerSocket serverSocket = new ServerSocket(11000);
- while (true) {
- Socket socket = serverSocket.accept();
- PrintWriter writer = new PrintWriter(socket.getOutputStream());
- BufferedReader readerIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- String line = null;
- while ((line = readerIn.readLine()) != null) {
- System.out.println(line);
- writer.println("你好,我已收到!");
- //writer.flush();//如果这里注释掉则无法收到客户端的消息,而且一直处于阻塞状态
- }
- readerIn.close();
- writer.close();
- socket.close();
- }
-
- }
- }
复制代码 我使用的就是PrintWriter 对象来输出消息的,为什么还要用flush来刷新缓存才能读到数据?
|