tcp编程:聊天室中的私聊

package com.sundear.demo.chat5;

import com.sundear.demo.chat3.SxtUtils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CopyOnWriteArrayList;

/**
* 在线聊天室:服务器
* 群聊
* 多线程
*/
public class Chat {
//高并发容器 线程安全
private static CopyOnWriteArrayList<Channel> all =new CopyOnWriteArrayList<Channel>();

public static void main(String[] args) throws IOException {
System.out.println("----server----");
ServerSocket server = new ServerSocket(8888);
while(true){
Socket client = server.accept();
System.out.println("一个客户建立了连接");
Channel c = new Channel(client);
all.add(c);//管理所有的成员
new Thread(c).start();
}

}
//一个客户等于一个Channel
static class Channel implements Runnable{
private DataInputStream dis;
private DataOutputStream dos;
private Socket client;
private boolean isRunning ;
private String name;
public Channel(Socket client){
this.client =client;
try {
dis =new DataInputStream(client.getInputStream());
dos =new DataOutputStream(client.getOutputStream());
isRunning =true;
//获取名称
this.name = receive();
this.send("欢迎你的到来");
sendOthers(this.name+"来了nono聊天室",true);
} catch (IOException e) {
release();
}


}
//接收消息
private String receive(){
String msg="";
try {
msg = dis.readUTF();
} catch (IOException e) {
System.out.println("----2---");
release();
}
return msg;
}
//发送消息
private void send(String msg){
try {
dos.writeUTF(msg);
} catch (IOException e) {
System.out.println("---3----");
release();
}
}

//群聊

/**
* 私聊
* @param msg
* @param isSys
*/
private void sendOthers(String msg,Boolean isSys){
Boolean isPrivate =msg.startsWith("@");
if(isPrivate){
//获取目标
int idx=msg.indexOf(":");
String targetName =msg.substring(1,idx);
msg =msg.substring(idx+1);
for(Channel other:all){
if(other.name.equals(targetName)){
other.send(this.name+"悄悄说:"+msg);
}
break;
}
}else {
for (Channel other : all) {
if (other == this) {
continue;
}
if (!isSys) {
other.send(this.name + ":" + msg);//群聊消息
} else {
other.send(msg);//系统消息
}

}
}
}

//释放资源
private void release(){
this.isRunning =false;
SxtUtils.close(dis,dos,client);
all.remove(this);
sendOthers(this.name+"离开了nono聊天室",true);
}



@Override
public void run() {
while(isRunning) {
String msg=receive();
if(!msg.equals("")){
//send(msg);
sendOthers(msg,false);
}
}
}
}
}
结合上一篇博客
posted @ 2021-07-15 18:33  下饭  阅读(69)  评论(0编辑  收藏  举报