发布时间:2026-09-28 17:37:35 浏览次数:1
以下是实现简单聊天室的完整攻略。
Java Web开发需要安装JDK、Tomcat等相关软件,具体步骤如下:
用HTML/CSS实现聊天室的前端页面,界面美观大方,同时方便用户操作。
以下是HTML代码示例:
<!DOCTYPE html><html><head> <title>聊天室</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="style.css"></head><body> <p id="chat-box"> <p id="chat-area"></p> <textarea id="send-box" placeholder="请输入消息"></textarea> <button id="send-btn">发送</button> </p> <script src="script.js"></script></body></html>用JavaScript实现聊天室的客户端逻辑,包括向后端发送消息、接收后端消息并渲染到页面中等。
以下是JavaScript代码示例:
var socket = new WebSocket("ws://localhost:8080/chat");socket.onopen = function() { console.log("连接已经打开");};socket.onmessage = function(event) { var data = JSON.parse(event.data); appendMsg(data.from, data.content);};function appendMsg(from, content) { var chatArea = document.getElementById("chat-area"); chatArea.innerHTML += from + ":" + content + "<br>";}function sendMsg() { var sendBox = document.getElementById("send-box"); var content = sendBox.value; if (content != "") { var data = { from: "我", content: content }; socket.send(JSON.stringify(data)); appendMsg(data.from, data.content); sendBox.value = ""; }}var sendBtn = document.getElementById("send-btn");sendBtn.addEventListener("click", sendMsg);用Java实现聊天室的服务器端逻辑,包括接收客户端连接、处理客户端消息并广播等。
以下是Java代码示例:
package com.example.chatroom;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;@ServerEndpoint("/chat")public class ChatEndpoint { private static List<Session> sessions = new ArrayList<>(); @OnOpen public void onOpen(Session session) { System.out.println("打开连接,SessionId:" + session.getId()); sessions.add(session); } @OnClose public void onClose(Session session) { System.out.println("关闭连接,SessionId:" + session.getId()); sessions.remove(session); } @OnMessage public void onMessage(String message, Session session) throws IOException { System.out.println("接收消息,SessionId:" + session.getId() + ",内容:" + message); String from = "匿名用户"; for (Session s : sessions) { if (s.getId().equals(session.getId())) { from = s.getRequestParameterMap().get("from").get(0); break; } } String response = "{\"from\":\"" + from + "\",\"content\":\"" + message + "\"}"; for (Session s : sessions) { s.getBasicRemote().sendText(response); } }}将静态文件和Java代码打包成WAR文件,将WAR文件放到Tomcat的webapps目录下即可部署和运行。
通过浏览器访问http://localhost:8080/index.html即可使用聊天室。
以下是两条关于聊天室使用的示例说明: