服务器端
public class ChatRoomServer {
// 聊天室中的成员
static List<Socket> socketList = new ArrayList<>();
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept(); // 等待客户端连接
socketList.add(socket); // 将新连接的socket存入集合
System.out.println(socket.getInetAddress() + "上线了...");
System.out.println(socketList);
}
// 读取&展示消息的线程
static class ReadMsgThread implements Runnable {
private Socket socket ;
public ReadMsgThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
boolean flag = true;
while (true) {
// 接收成员发送的消息
//获取输入流 读取消息
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int read = in.read(bytes);
// 张三&你好
String msg = new String(bytes , 0 ,read);
// 解析
String[] split = msg.split("&");
String nickName = split[0]; // 昵称
String content = split[1]; // 要发送的内容
if (flag){
System.out.println(nickName + "上线了...");
flag = false;
}
System.out.println(nickName + "说:" + content);
}
} catch (Exception e) {
// e.printStackTrace();
}
}
}
客户端
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 9999);
// 启动接收 服务端 群发消息的线程
new Thread( new ReadServerMsg(socket)).start();
Scanner sc = new Scanner(System.in);
System.out.println("请设置您的昵称:");
String nickName = sc.next() ;
while (true){
OutputStream out = socket.getOutputStream();
System.out.println("请输入您要发送的内容:");
String content = sc.next();
// 打包信息 昵称 与 内容 使用 & 连接
// 张三&你好
String msg = nickName + "&" + content ;
out.write(msg.getBytes());
}
}
static class ReadServerMsg implements Runnable{
private Socket socket ;
public ReadServerMsg(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try{
while (true){
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int read = in.read(bytes);
String msg = new String(bytes , 0 , read);
System.out.println("server:" + msg);
}
}catch (Exception e ){
}
}
}
}