把 System.out.println(reader.readLine()); 这句去掉
把 bw.close(); 去掉
下面是你的代码,运行试试
客户端
package com.pzr.demo20161021;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class demo3 {
public static void main(String args[]){
try {
Socket socket = new Socket("127.0.0.1",8888);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while(true){
System.out.println("请输入消息:");
// System.out.println("服务器发过来的消息:"+reader.readLine());
bw.write(br.readLine());
bw.newLine();
bw.flush();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端
package com.pzr.demo20161021;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class demo4 {
public static void main(String args[]){
try {
ServerSocket serverSocket =new ServerSocket(8888);
Socket socket = serverSocket.accept();
System.out.println(socket.getInetAddress().getHostAddress()+"已连接");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter witer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String string = null;
while((string = reader.readLine()) != null){
System.out.println(string);
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((string = br.readLine()) != null){
witer.write(string);
witer.newLine();
witer.flush();
}
reader.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}