欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

toString() unavailable,

来源: javaer 分享于  点击 46224 次 点评:5

toString() unavailable,


最近在练习java的socket

自己写了个例子代码如下:

server端

public class WeatherServer {

/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket serverSocket=new ServerSocket(12345);
System.out.println("启动天气查询...");

Socket socket=serverSocket.accept();
System.out.println("开始接受数据");

//接收客户端的消息
InputStream in=socket.getInputStream();
/*System.setIn(in);
Scanner scanner=new Scanner(System.in);
while(scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}*/
byte[] b=new byte[6];
int len=0;
String acceptMessage="";
while((len=in.read(b))!=-1){
String s=new String(b,0,len,"UTF-8");
acceptMessage+=s;
}
System.out.println("from the client..."+acceptMessage);

//响应给客户端的消息
String responseMessage="晴";
OutputStream out=socket.getOutputStream();
byte[] b1=responseMessage.getBytes();
out.write(responseMessage.getBytes());
System.out.println("to the client..."+responseMessage);
in.close();
out.close();
}
}


client端:

public class WeatherClient {

/**
* @param args
* @throws IOException 
* @throws UnknownHostException 
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket=new Socket("127.0.0.1",12345);
//向服务器端发送消息
OutputStream out=socket.getOutputStream();
String sendMessage="tttt\n";
byte[] bb=sendMessage.getBytes();
out.write(sendMessage.getBytes());
out.flush();
// out.close();
// socket.shutdownOutput();
System.out.println("to the server..."+sendMessage);

//接收服务器端返回的消息
InputStream in =socket.getInputStream();
byte[] b=new byte[5];
int len=in.read(b);
String responseMessage="";
while((len=in.read(b))!=-1){
String s=new String(b,0,len,"UTF-8");
responseMessage+=s;
}
System.out.println("from the server..."+responseMessage);


in.close();
socket.close();
}


}

什么情况会出现这个问题?

代码一运行没有报错,输入流和输出流之间形成了死锁。由于client端的输出流没有告诉server端流已经结束,所以server端在等待client端的输出流,而client在等待server端的响应输出流,server端没有结束接收client端的输出,server也不会响应消息给client端。所以造成了死锁的现象。

用debugger模式可以看到server端的输入流出现这个提示:toString() unavailable - no suspended threads

我们在client端输出结束后加上这么一句:socket.shutdownOutput();就可以告诉server端,流已经结束



相关文章

    暂无相关文章

用户点评