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

yskshr 2017-09-03 11:06:31
客户端
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();
}
}
...全文
181 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
yskshr 2017-09-04
  • 打赏
  • 举报
回复
引用 1 楼 rayw0ng的回复:
readLine 需要读到换行符才能返回,所以需要加个换行符 "\n"。
多谢,多谢,问题解决了。
WonHyo 2017-09-04
  • 打赏
  • 举报
回复
在客户端client的out.flush后面加上 out.shutdownOutput
rayw0ng 2017-09-04
  • 打赏
  • 举报
回复
readLine 需要读到换行符才能返回,所以需要加个换行符 "\n"。

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧