//服务器端
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();
}
}
}
为什么这样写死循环 在客户机发给服务器消息 服务器回复后就出现这样的异常?
怎么修改才正确呢?
错误异常意思是socket被关闭了。按你的代码while(true)死循环里的socket.shutdownOutput();socket.shutdownInput();其实际意思是当前socket的输入和输出已经被关闭,不管服务器输入或客户端输出数据都不行了,因此程序会崩掉。
按照一楼的回答,就是要在while循环里把这两句代码删了就可以;或者我的另一个想法就是把Socket socket = new Socket("127.0.0.1", 8888);这句代码放进while循环中,让它每循环一次都建新的socket对象,但这种做法较耗内存资源。
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();
提前关闭了一次socket.删除这行试试