우선, 나는 당신에게 선언하고 싶습니다 : JDK 7이 필요합니다. Tomcat은 WebSocket 버전을 지원해야합니다.
1. initservlet
이 클래스는 주로 사용자 아이덴티티 정보의 향후 저장을 구성하는 맵 저장소를 초기화하고, 초기화 메소드를 사용하여 저장소를 초기화하고, 정적 메소드 getSocketList를 사용하여 해당 사용자 ID 정보를 얻는 데 사용됩니다.
WebSocket, MessageInbound는 로그인의 정보를 식별하고 해당 사람을 찾아서 푸시 메시지를 사용하는 데 사용된다고 생각합니다. 각 로그인은 MessageInbound가 생성됩니다.
여기서 Hashmap <String, MessageInbound> : String은 사용자 세션의 로그인 ID를 저장하고 MessageInbound는 푸시에 필요한 신분 정보를 저장합니다. 위의 것은 개인적인 구두 이해입니다.
패키지 소켓; import java.nio.charbuffer; java.util.arraylist 가져 오기; java.util.hashmap import; Java.util.list 가져 오기; javax.servlet.servletconfig import; javax.servlet.servletexception import; import javax.servlet.http.httpservlet; import org.apache.catalina.websocket.messageInbound; 공개 클래스 initservlet는 httpservlet {private static final long serialversionuid = -l; // 비공개 정적 목록 <MessageInbound> socketlist; 개인 정적 해시 맵 <String, MessageInbound> SocketList; public void init (servletconfig config) servletexception {// initservlet.socketlist = new ArrayList <MessageInbound> (); initservlet.socketlist = new Hashmap <String, MessageInbound> (); super.init (config); System.out.println ( "서버 시작 ============"); } public static hashmap <string, messageInbound> getSocketList () {return initservlet.socketList; } /* public static list <MessageInbound> getSocketList () {return initservlet.socketList; } */} 2. MywebsocketServlet
WebSocket은 연결 서블릿을 설정하는 데 사용됩니다. 연결을 설정할 때 먼저 로그인 us userID를 가져 와서 MyMessageInbound 생성자를 호출 할 때 userID를 통과하십시오.
패키지 소켓; import java.io.ioexception; import java.io.printwriter; import java.nio.charbuffer; javax.servlet.servletexception import; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.catalina.websocket.streaminbound; import org.apache.catalina.websocket.websocketServlet; / ** * * * @className : myWebSocketServlet * @description : 연결을 설정할 때 생성 * @Author Mangues * @Date -/ public class myWebSocketServlet {public string getUser (httpservletRequest request) {String username = (string) request.getSENTION ( "USER"); if (username == null) {return null; } 리턴 사용자 이름; // return (string) request.getAttribute ( "사용자"); } @Override Protected StreamInbound CreateWeBSocketInbound (String arg, httpservletrequest request) {System.out.println ( "#############"); 새로운 myMessageInbound (this.getUser (요청))를 반환합니다. }} 3. Onopen 메소드는 initservlet의 맵 ID 리포지토리를 호출합니다.
로그인 한 사용자 MessageInbound에 해당하는 사용자 userId 및 WebSocket ID 정보를 넣으십시오 (userID는 MessageInbound를 푸시하는 데 필요한 ID를 찾는 데 사용할 수 있습니다).
ontextMessage : 메시지를 받고 메시지를 보내는 데 사용됩니다
패키지 소켓; import java.io.ioexception; import java.nio.bytebuffer; import java.nio.charbuffer; java.util.hashmap import; import org.apache.catalina.websocket.messageInbound; import org.apache.catalina.websocket.wsoutbound; Util.MessageUtil 가져 오기; Public Class MyMessageInbound는 MessageInbound {개인 문자열 이름; public mymessageInbound () {super (); } public myMessageInbound (문자열 이름) {super (); this.name = 이름; } @override protected void onbinarymessage (Bytebuffer arg)는 ioexception {// todo 자동 생성 메소드 스터브} @override protected void void ontextMessage (charbuffer msg)를 {// hashmap <string, string (string)에 의해 보내진 메시지 다음에 맵을 던졌습니다. // 메시지 클래스 처리 // 업라인 사용자 컬렉션 클래스 맵 Hashmap <String, MessageInbound> usermsgmap = initservlet.getSocketList (); 문자열 fromname = messagemap.get ( "FromName"); // 메시지는 userId String toname = messagemap.get ( "toname")에서 나옵니다. // 메시지가 사용자의 userId로 전송됩니다. // usermessageInbound MessageInbound = usermsgmap.get (toname); // (MessageInBound! = null) if if (messageInbound가 창고에서 사용자에게 전송 된 메시지 {// 메시지가 사용자에게 존재하는 경우 wsoutbound outBound = messageInbound.getWsoutBound (); 문자열 content = messagemap.get ( "content"); // 메시지 내용을 가져옵니다. 문자열 msgcontentstring = fromName + "" + content; // 전송 된 메시지 구성 // 컨텐츠를 보내기 charBuffer tomsg = charBuffer.wrap (msgcontentstring.tochararray ()); outbound.writetextMessage (TOMSG); // outbound.flush (); } /* for (messageInbound messageInbound : initservlet.getSocketList ()) {charBuffer buffer = charBuffer.wrap (msg); wsoutbound outbound = messageinbound.getwsoutbound (); outbound.writetextMessage (버퍼); outbound.flush (); } */} @override protected void onclose (int status) {initservlet.getSocketList (). remove (this); super.onclose (상태); } @override protected void onopen (wsoutbound outbound) {super.onopen (아웃 바운드); // 로그인 if (name! = null) {initservlet.getSocketList (). put (name, this); } // initservlet.getSocketList (). add (this); }} 4. 메시지 처리 클래스, 프론트 엔드에서 보낸 메시지 처리 메시지
패키지 유틸리티; import java.nio.charbuffer; java.util.hashmap import; / ** * * * @className : messageUtil * @Description : 메시지 처리 클래스 * @Author Mangues * @Date - */ public class agestUtil {public static hashmap <string, string> getMessage (charBuffer msg) {hashmap <string, map = new Hashmap <String> (); 문자열 m [] = msgstring.split ( ","); map.put ( "FromName", m []); map.put ( "toname", m []); map.put ( "content", m []); 리턴 맵; }} 5. 웹 구성
<? xml version = "1.0"encoding = "utf-8"?> <web-app version = "3.0"xmlns = "http://java.sun.com/xml/xml/ns/javaee"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance. xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name> mywebsetket </servlet-name> <servlet-class.mywebsocketServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> mywebsocket </servlet-name> <url-pattern>* <Load-on-Startup> 1 </load-on-startup> </servlet> <welcome-file-list> <welcome-file> index.jsp </welcome-file> </welcome-file-list> </web-app>
6. 프론트 엔드, 편의를 위해 나는 두 개의 JSP를 직접 사용하고 <%session.setattribute ( "사용자", "Xiao Ming")%>를 사용하여 로그인을 나타냅니다.
두 JSP 사이에는 필수적인 차이가 없으며 두 사람이 로그인 한 것을 나타내는 데 사용됩니다. 동일한 브라우저에서 다른 JSP를 열 수 있습니다.
A. 최소화하십시오
<%@ page language = "java"contmenttype = "text/html; charset = utf-"pageencoding = "utf-"%> <! doctype html> <html> <head> <meta http-equiv = "content-type"content = "text/html; type = "text/javaScript"src = "js/jquery ... min.js"> </script> <%session.setAttribute ( "user", "minimize");%> <script type = "text/javascript"> var ws = null; 함수 startWebSocket () {if (Window의 'WebSocket') ws = new WebSocket ( "ws : // localhost : /websocket/mywebsocket.do"); else if (창에 'mozwebsocket') ws = new mozwebsocket ( "ws : // localhost : /websocket/mywebsocket.do"); 그렇지 않으면 경고 ( "지원되지 않음"); ws.onmessage = function (evt) {//alert(evt.data); Console.log (EVT); $ ( "#xiaoxi"). val (evt.data); }; ws.onclose = function (evt) {// alert ( "close"); document.getElementById ( 'denglu'). innerhtml = "오프라인"; }; ws.onopen = function (evt) {// alert ( "Open"); document.getElementById ( 'denglu'). innerhtml = "온라인"; document.getElementById ( 'username'). innerHtml = '최소화'; }; } function sendmsg () {var fromName = "minimize"; var toname = document.getElementById ( 'name'). 값; // var content = document.getElementById ( 'writemsg')에게 보내십시오. 값; // 컨텐츠 보내기 ws.Send (fromName+","+toname+","+content); } </script> </head> <body onload = "startwebsocket ();"> <p> 채팅 함수 구현 </p> 로그인 상태 : <span id = "denglu"style = "color : red;"> 로그인> <br> 로그인 사람 : <span id = "username"> </span> <br> <br> <input typ to thor to thor to value = "xiao ming"> </input> <br> 컨텐츠 보내기 : <input type = "text"id = "writems"> </input> <br> 채팅 상자 : <textArea rows = ""cols = ""readonly id = "Xiaoxi"> </textarea> <br> <input type = "valling"onclick = "sendmms ="sendmms = "value" </html> B. Xiao Ming
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html> <html> <head> <meta http-equiv = "content-type"content = "text/html; itf-8"> </title> <title> "text/javaScript"src = "js/jquery 2.1.min.js"> </script> <%session.setAttribute ( "user", "xiao ming");%> <script type = "text/javaScript"> var ws = null; 함수 startWebSocket () {WINDOCKECT (WINDOCTOC) wS = 새로운 WebSocket ( "ws : // localhost : 8080/websocket/mywebsocket.do"); else if (창에 'mozwebsocket') ws = new mozwebsocket ( "ws : // localhost : 8080/websocket/mywebsocket.do"); 그렇지 않으면 경고 ( "지원되지 않음"); ws.onmessage = function (evt) {console.log (evt); //alert (evt.data); $ ( "#xiaoxi"). val (evt.data); }; ws.onclose = function (evt) {// alert ( "close"); document.getElementById ( 'denglu'). innerhtml = "오프라인"; }; ws.onopen = function (evt) {// alert ( "Open"); document.getElementById ( 'denglu'). innerhtml = "온라인"; document.getElementById ( 'username'). innerHtml = "Xiao Ming"; };} 함수 sendmsg () {var fromName = "Xiao Ming"; var toname = document.getElementById ( 'name'). 값; // var content = document.getElementById ( 'writemsg')에게 보내십시오. 값; // 컨텐츠 전송 ws.send (fromname+","+toname+","+content);}} </script> </head> <body onload = "startwebsocket ();"> <p> 채팅 함수 구현 </p> 로그인 로그인 로그인 : <span id = "denglu"style = "color : red in <br> <br> 인 Person : id = "username"> </span> <br> <br> <br> 보내기 : <input type = "text"id = "name"value = "value ="minimize "> </input> <br> 컨텐츠 보내기 : <input type ="text "id ="writems "> </input> <br> 채팅 상자 : <textArea rows ="100 "Readonly id = "xiaoxi"> </textarea> <br> <input type = "button"value = "send"onclick = "sendmsg ()"> </input> </body> </html>위의 것은 Javaweb Websocket을 사용하여 간단한 P2P 채팅 기능 예제 코드를 구현하는 데 대한 관련 지식입니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!