2 yskshr yskshr 于 2017.09.03 21:41 提问

求教一个关于客户端与服务器端交互的问题

客户端
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s=new Socket("LocalHost",8888);
PrintWriter out=new PrintWriter(s.getOutputStream());
out.write("ni hao");
out.flush();
BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(in.readLine());//这里会一直为阻塞状态
out.close();
}
}
服务器端
public class Server {
public static void main(String[] args) throws IOException {
Socket s=null;
ServerSocket ss=new ServerSocket(8888);
s=ss.accept();
BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(in.readLine())];
//这里也为阻塞状态,如果将客户端的out.close();写到客户端的in.readLine()
前又会报Exception in thread "main" java.net.SocketException: Socket is closed at java.net.Socket.getInputStream(Unknown Source)错误,求解决方法

PrintWriter pw=new PrintWriter(s.getOutputStream());
pw.write("hello");
pw.flush();
pw.close();
}
}

1个回答

Small_Mouse0
Small_Mouse0   Ds   Rxr 2017.09.04 09:12
已采纳

读写之前加个判断
判断socket没有关闭,,!client.isClosed()

我前几天写的一个博客,,关于socket的题主可以参考参考:http://blog.csdn.net/small_mouse0/article/details/77758158

Csdn user default icon
上传中...
上传图片
插入图片