Java Socket 阻塞问题 求解
服务器端
public class DayTimeServer {
public static void main(String[] args){
ServerSocket server=null;
try {
//服务器端8080端口
server=new ServerSocket(8080);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
return;
}
int i=0;
while(true){
Socket socket = null;
try {
socket = server.accept();
// BufferedInputStream bIn=new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bOut=new BufferedOutputStream(socket.getOutputStream());
BufferedWriter bWriter=new BufferedWriter(new OutputStreamWriter(bOut,"ASCII"));
bWriter.write((new SimpleDateFormat("yyyy-MM-dd")).format(new Date()));
bWriter.flush();
System.out.println(++i);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}/* finally{
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}*/
}
}
}
客户端:
public class Client {
public static void main(String[] args) {
InetSocketAddress address = null;
address = new InetSocketAddress("127.0.0.1", 8080);
int i = 0;
while (true) {
Socket socket = null;
try {
socket = new Socket();
socket.connect(address);
BufferedInputStream bIn = new BufferedInputStream(socket.getInputStream());
int c;
while ((c = bIn.read()) != -1) {
System.out.print((char) c);
}
System.out.println(++i);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
}
}
服务器端socket.close()被注释掉后,会造成客户端阻塞,不晓得why? 求解
[解决办法]
当你在服务端注释掉close方法后,客户端这种接收方式,是不晓得服务端是否已经传输完数据,此时客户端还在等待服务端传来的数据(其实数据已经传完了,但客户端却无法判断出来,所以一直还在接收数据)当然会阻塞了。
两种改进方法:
1、如果单纯的发送字符串数据可以用PrintWrite(.println())发送,接收时用BufferedReader(.readLine())
2、使用字节数组。write(byte[]),服务端告知客户端发送多少字节的数据,,客户端一旦接收完这么多数据就退出循环。
[解决办法]
按照楼上的,用字节数组或者readline读取吧