/** * 客户端接收消息的线程 */ public class ReadClientThread extends Thread { private InputStream inputStream; public ReadClientThread(InputStream inputStream){ this.inputStream=inputStream; } public void run(){ while (true){ String msg=readMessage(inputStream); if(Config.ExitCode.equals(msg)){ System.out.println("聊天已关闭,谢谢使用!"); break; } System.out.println(msg); } } /** * 读取信息 * 这里使用BufferedReader的readLine方法的话会造成堵塞 * @param ins */ public String readMessage(InputStream ins) { String clinetMessage=""; try { int value = ins.read(); while (value != 10) { // 代表客户单不正常关闭 if (value == -1) { //throw new Exception(); clinetMessage=Config.ExitCode; break; } clinetMessage = clinetMessage + (char) value; value = ins.read(); } clinetMessage = clinetMessage.trim(); }catch (Exception e){ clinetMessage=Config.ExitCode; System.out.println("聊天服务器异常!"); //e.printStackTrace(); } return clinetMessage; } }