socket服务端必须先写后读吗?简单服务端与客户端例子卡住

iheheyou 2016-08-25 09:16:15
运行程序,客户端和服务端都卡住了,然后我关掉客户端,结果服务端也退出了,为什么会卡住?怎么回事?
客户端:

public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
try(Socket s=new Socket("127.0.0.1", 9080);) {
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
Scanner in=new Scanner(s.getInputStream());
out.write("i am client");
while(in.hasNextLine()){
System.out.println(in.nextLine());
}
}
}
}



服务端

public class Server {

public static void main(String[] args) throws IOException {
try(ServerSocket ser = new ServerSocket(9080)){
try(Socket soc= ser.accept()){;
PrintWriter out=new PrintWriter(soc.getOutputStream(),true);
Scanner in = new Scanner(soc.getInputStream());
while(in.hasNextLine()){
System.out.println(in.nextLine());
}
out.println("i am server");
}
}
}

}



...全文
200 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
iheheyou 2016-08-26
  • 打赏
  • 举报
回复
引用 1 楼 hemowolf 的回复:
socket 的服务端/客户端只是针对建立连接而言的,连接建立好之后,双方通信地位是相同的,不存在一定要一端发送,另一端才能接收的问题 你的程序里,两端都没有向对方发送数据,但是两端却又都在等待接收对方发送的数据,造成了死锁
我发现实关闭流的问题: 我把代码改了一下:

public class Server {
	public static void main(String[] args) throws IOException {
		try(ServerSocket ser = new ServerSocket(9080)){
			try(Socket soc= ser.accept()){;
				Scanner in = new Scanner(soc.getInputStream());
				while(in.hasNextLine()){
					System.out.println(in.nextLine());
				}
				in.close();
			}
		}
	}

}

public class Client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		try(Socket s=new Socket("127.0.0.1", 9080);) {
			PrintWriter out=new PrintWriter(s.getOutputStream(),true);
			Scanner in=new Scanner(s.getInputStream());
			out.write("i am client");
			out.flush();
			out.close();
		}
	}
}
然后我调试,服务端执行到 while(in.hasNextLine()){ 这里阻塞了,客户端开始执行out.write("i am client");再执行flush,可是服务端依然阻塞,直到执行了close,服务端才走到下一行,这是怎么回事?难道flush没什么用?
老许要老婆么 2016-08-26
  • 打赏
  • 举报
回复
楼主试试 给客户端和服务端各增加一个线程来通信
小灰狼 2016-08-26
  • 打赏
  • 举报
回复
socket 的服务端/客户端只是针对建立连接而言的,连接建立好之后,双方通信地位是相同的,不存在一定要一端发送,另一端才能接收的问题 你的程序里,两端都没有向对方发送数据,但是两端却又都在等待接收对方发送的数据,造成了死锁
小灰狼 2016-08-26
  • 打赏
  • 举报
回复
接收端你调用的是 nextLine,这会要求 Scanner 在读取到回车换行符才会返回 发送端你并没有送回车换行符,所以接收端一直等你送回车换行符,把 out.write("i am client"); 改为 out.write("i am client\r\n"); 试试

62,614

社区成员

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

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