在java的网络编程中使用TCP协议在Client端和Server端循环收发消息时,如果用的是BufferedReader和BufferedWriter,出现Client端只能发送一次消息,当发送第二次消息时,Server端已经关闭的情况,具体报错为:Socket output is already shutdown或者是由于以前的关闭调用,套接字在那个方向已经关闭,发送或接收数据的请求没有被接受。
解决方案为Client端发送完消息后不要写 socket.shutdownOutput();
,直接bw.write(line); bw.newLine(); bw.flush();
就行,写正确的代码实例如下:
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
//Client端
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",10086);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner sc = new Scanner(System.in);
String line;
while(true){
System.out.println("请输入要发送的内容:");
line = sc.nextLine();
bw.write(line);
bw.newLine();
bw.flush();
//后面不要加 socket.shutdownOutput();
line = br.readLine();
System.out.println(line);
}
}
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10086);
Socket socket = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String line;
while(true){
line = br.readLine();
System.out.println(line);
//回写数据
bw.write("数据收到了");
bw.newLine();
bw.flush();
//这里也不用写
}
}
}
按照上面的形式写代码,就可以循环发送数据了