yskshr
yskshr
2017-09-03 13:41
采纳率: 100%
浏览 874
已采纳

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

客户端
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
    鼠小 2017-09-04 01:12
    已采纳

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

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

    点赞 评论

相关推荐