本案例模拟聊天室,有着群发和私聊的功能,一切都在console中进行,没有界面,采用oop思想,封装操作
代码如下:
服务器端:服务端需要连接多个客户端,因此需要循环监听,每次连接一个客户端创建一个Channel线程,然后再次阻塞式监听。
package com.chatroot.java;
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> list = new CopyOnWriteArrayList<Chat.Channel>();//线程安全容器
private static int count = 0;
public static void main(String[] args) throws IOException {
System.out.println("-----服务器端-----");
ServerSocket server = new ServerSocket(9999);
while(true) {
Socket client = server.accept();
Channel c = new Channel(client);
list.add(c);
count++;//记录连接客户端的数目
System.out.println("一个客户端建立连接");
System.out.println("当前客户端数目为:"+count);
new Thread(c).start();
}
}
static class Channel implements Runnable{
private DataInputStream dis = null;
private DataOutputStream dos = null;
private Socket client;
private String name;
private boolean isRunning;
public Channel(Socket client) {
this.client = client;
try {
isRunning = true;
dis = new DataInputStream(client.getInputStream());
dos = new DataOutputStream(client.getOutputStream());
this.name =