基于控制台的Java聊天室
IDEA用户可以直接到我的github项目页面下载使用 https://github.com/yanghao1550/Chat-Room-Java
该小项目主要使用Socket
以及多线程入门知识完成。
Chat.java
是服务器端 Client.java
是客户端
使用时需要先打开服务器端,再打开多个客户端连接到服务器端进行交流。
主要功能有:
1、欢迎新用户并广播有新用户上线
2、群聊以及私聊功能(默认为群聊,私聊方式为输入"@用户名:message")
3、用户退出提醒
客户端需要保证new Socket()
中服务器端IP地址的正确性,如果服务器端是本机,则输入"localhost"
即可
代码
Chat.java
/**
* 在线聊天室:服务器端
*
* @Author Nino 2019/10/23
*/
public class Chat {
private static CopyOnWriteArrayList<Channel> all = new CopyOnWriteArrayList<>();
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();
}
}
static class Channel implements Runnable{
private Socket client;
private DataInputStream dis;
private DataOutputStream dos;
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;
name = receive();
this.send("欢迎");
this.sendOthers(name + "来到了聊天室",true);
} catch (IOException e) {
e.printStackTrace();
release();
}