用java写的,socket连接后另开一个线程实时监听输入流,但是如果服务器那边发生异常中断了,我这边也利用心跳机制知道有异常,需要断掉socket重新连,但是监听输入流的线程就卡在read的那个方法里了,怎么才能从那个read的阻塞里出来呢?
import java.net.*;
import java.io.*;
public class Server{
public static void main(String[] args){
InputStream in=null;
OutputStream out=null;
try{
ServerSocket ss=new ServerSocket(8888);
Socket socket=ss.accept();
in=socket.getInputStream();
out=socket.getOutputStream();
DataOutputStream dos=new DataOutputStream(out);
DataInputStream dis=new DataInputStream(in);
String s=null;
if((s=dis.readUTF())!=null){
System.out.println(s);
}
/*
System.out.println(dis.readUTF())
*/
String fileContent = readFileContent("E:\\LQ.txt");;
dos.writeUTF(fileContent);
dis.close();
dos.close();
socket.close();
}catch(IOException e) {
e.printStackTrace();
}
}
private static String readFileContent(String fileName) throws IOException {
File file = new File(fileName);
BufferedReader bf = new BufferedReader(new FileReader(file));
String content = "";
StringBuilder sb = new StringBuilder();
while(content != null){
content = bf.readLine();
if(content == null){
break;
}
sb.append(content.trim());
}
bf.close();
return sb.toString();
}
}
import java.net.*;
import java.io.*;
public class Client{
public static void main(String[] args){
InputStream is=null;
OutputStream os=null;
try{
Socket socket=new Socket("localhost",8888);
is=socket.getInputStream();
os=socket.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
dos.writeUTF("hello");
String s=null;
if((s=dis.readUTF())!=null);
System.out.println(s);
dis.close();
dos.close();
socket.close();
}catch(IOException e) {e.printStackTrace();}
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。