communicatethread.java

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

JAVA
62
字号
import java.io.*;
import java.net.*;

public class CommunicateThread extends Thread{
    protected Socket socket;
    protected BufferedReader in=null;
    protected PrintWriter out;
    Server_Socket server;
    boolean isTrue=true;
    java.util.Vector inforStack;
    int index;

    CommunicateThread(Socket s,Server_Socket s1,int i)throws IOException{     //初始化
        socket=s;
        server=s1;
        index=i;
        inforStack=new java.util.Vector();
        in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
        this.start();
    }

    public void run(){
        String infor;
        try{
            while(isTrue){
                infor=in.readLine();               //读入缓冲区读进消息并做出判断
                if(infor.equals("Client exit!")){
                        writeInformation(infor);
                        isTrue=false;
                }
                else if(infor!=null){
                     writeInformation(infor);
                }
                try{
                    Thread.sleep(100);
                }catch(InterruptedException ex){}
                }
        }catch(IOException e){ ;}
        finally{
            try{
                in.close();
                out.close();
                socket.close();
                server.clients.remove(index);
                Server_Socket.index--;
            }catch(IOException ei){;}
        }
    }

    public void writeInformation(String infor){          //存储所接受到的消息
        inforStack.add(infor);
    }

    public void sendInformation(String str){            //输出流输出消息
        try{
            out.println(str);
            out.flush();
        }catch(Exception e){;}
    }

}

⌨️ 快捷键说明

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