怎么实现客户端与服务器端 不停的相互发消息
//服务器端
package 通讯;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class server {
public static void main(String[] args) {
try {
ServerSocket serversocket = new ServerSocket(8888);
System.out.println("正在等待连接。。。。。。。");
Socket socket = serversocket.accept();
while(true){//死循环重复
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s;
while ((s = br.readLine()) != null) {
System.out.println("客户端说" + s);
}
socket.shutdownInput();
OutputStream os = socket.getOutputStream();
PrintStream bw = new PrintStream(os);
Scanner input = new Scanner(System.in);
System.out.println("你想对对面的客户机说些什么");
bw.print(input.next());//从键盘输入读取一行打印到输出流
bw.flush();
socket.shutdownOutput();
bw.close();
os.close();
br.close();
isr.close();
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//客户端
package 通讯;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class client {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 8888);
while (true) {//死循环重复步骤
OutputStream os = socket.getOutputStream();
PrintStream bw = new PrintStream(os);
Scanner input = new Scanner(System.in);
System.out.println("你想对对面的服务器说些什么");
bw.print(input.next());//从键盘输入读取一行 打印到输出流
bw.flush();
socket.shutdownOutput();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s;
while ((s = br.readLine()) != null) {
System.out.println("服务器端说:" + s);
}
socket.shutdownInput();
br.close();
isr.close();
is.close();
bw.close();
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
为什么这样写死循环 在客户机发给服务器消息 服务器回复后就出现这样的异常?
怎么修改才正确呢?