当前位置: 首页 > 工具软件 > ChatDemo > 使用案例 >

java线程多用户_java多线程,多用户聊天室,原理模型【ChatDemo】

郑翰海
2023-12-01

socketList;

private Socket socket;

private BufferedReader bufferedReader;

public ChatThread(Socket socket,ListsocketList){

this.socket=socket;

this.socketList=socketList;

}

private void preRun(){

InputStreamReader r=null;

try {

r = new InputStreamReader(this.socket.getInputStream());

this.bufferedReader=new BufferedReader(r);

} catch (IOException e) {

e.printStackTrace();

}

}

private PrintWriter getSocketPrintWriter(Socket socket){

OutputStream os=null;

try {

os = socket.getOutputStream();

} catch (IOException e) {

e.printStackTrace();

}

OutputStreamWriter osw=new OutputStreamWriter(os);

BufferedWriter bw=new BufferedWriter(osw);

return new PrintWriter(bw, true);

}

private void broadcast(String msg){

for(Socket s:socketList){

PrintWriter pw=this.getSocketPrintWriter(s);

pw.println(msg);

}

}

public void run() {

String msg="";

this.preRun();

while(true){

try {

msg="from client "+this.bufferedReader.readLine();

this.broadcast(msg);

} catch (IOException e) {

try {

this.bufferedReader.close();

this.socket.close();

this.socketList.remove(this.socket);

this.broadcast("somebody exist....people size :"

+socketList.size());

} catch (IOException e1) {

e1.printStackTrace();

}

e.printStackTrace();

return ;

}

}

}

}

/********************************************************************

客户端类ChatClient,CTGetMessage,CTSendMessage

*********************************************************************/

import java.io.*;

import http://www.doczj.com/doc/323e56210722192e4536f635.html.*;

import java.util.Scanner;

public class ChatClient {

public static void main(String[] args) throws Exception {

Socket socket=new Socket("127.0.0.1", 6666);

Scanner sc=new Scanner(System.

 类似资料: