communicatethread.java

来自「用Java编写的基于Socket的聊天室小程序!」· Java 代码 · 共 75 行

JAVA
75
字号
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

class CommunicateThread extends Thread{//保持连接线程
 protected Socket clientSock;
 protected BufferedReader in=null;
 protected PrintWriter out;
 ChatRoomServer chatFrame;
 boolean isTrue=true;//run()
 java.util.Vector inforStack;
 int index2;//

 public CommunicateThread(Socket Sock,ChatRoomServer cFrame,int index){
  clientSock=Sock;
  chatFrame=cFrame;
  index2=index;
  inforStack=new java.util.Vector();
  try{
   in=new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
   out=new PrintWriter(clientSock.getOutputStream());
  }catch(IOException ei){
   try{
    clientSock.close();
   }catch(IOException ei2){ }
   chatFrame.processMsg(ei.toString());
   return;
  }
  this.start();
 }

 public void run(){
  String infor;
  try{
   while(isTrue){
    infor=in.readLine();
    if(infor.equals("Client exit!")){
     writeInformation(infor);//把信息写到信息栈,以倍广播出去
     stopRun();
    }else if(infor!=null){
     writeInformation(infor);
    }//else break;
    try{
     Thread.sleep(100);//version2
    }catch(InterruptedException ex){}
   }
  }catch(IOException e){ ;}
  finally{
   try{
    in.close();
    out.close();
    clientSock.close();
    chatFrame.clients.remove(index2);//在clients中清除本线程序
    ChatRoomServer.index--;//
   }catch(IOException ei){;}
  }

 }

 public void writeInformation(String infor){//写信息栈
  inforStack.add(infor);
 }

 private void stopRun(){//终止线程
  isTrue=false;
 }

 public void sendInformation(String str){//发送信息
  try{
   out.println(str);
   out.flush();
  }catch(Exception e){;}
 }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?