이 기사에서는 Java Websocket의 특정 코드를 공유하여 참조를위한 채팅 메시지 푸시 함수를 구현합니다. 특정 내용은 다음과 같습니다
환경:
JDK.1.7.0_51
Apache-Tomcat-7.0.53
Java Jar 패키지 : Tomcat-Coyote.jar, Tomcat-juli.jar, WebSocket-Api.jar
채팅 메시지 보내기 클래스 :
import java.io.ioexception; import java.util.hashmap; import java.util.map; import java.util.concurrent.atomic.atomicinteger; import javax.websocket.onclose; import javax.websocket.onerror; import javax.websocket.onmessage; import javax.websocket.onopen; import javax.websocket.session; import javax.websocket.server.serverendpoint; import org.apache.juli.logging.log; org.apache.juli.logging.logfactory; import com.util.htmlfilter; /*** WebSocket 메시지 푸시 서비스 클래스* @Author hu Hansan** 2014-11-18 7:53:13 pm*/ @serverendpoint (value = "/webSocket/Chat") 공개 클래스 채팅 {private static final log = logfactory.getLog (chatannotation.class); 개인 정적 최종 문자열 guest_prefix = "게스트"; 개인 정적 최종 Atomicinteger Connections = New Atomicinteger (0); 비공개 정적 최종 맵 <문자열, 개체> 연결 = new Hashmap <문자열, 개체> (); 개인 최종 문자열 별명; 개인 세션 세션; public chatannotation () {nickname = guest_prefix + connections.getAndIncrement (); } @onopen public void start (세션 세션) {this.session = session; Connections.put (별명, this); String Message = String.format ( "* %s %s", 닉네임, "가입되었습니다."); 방송 (메시지); } @onclose public void end () {connections.remove (this); String Message = String.format ( "* %s %s", 닉네임, "연결이 끊어졌습니다."); 방송 (메시지); } / *** 메시지 보내기 트리거 메소드 전송* @param 메시지* / @onmessage public void Incoming (문자열 메시지) {// 클라이언트 문자열 filterdmessage = string.format ( " %s : %s", 닉네임, htmlfilter.filter (message.toString ()); 브로드 캐스트 (Filtersmessage); . } / *** 메시지 보내기 메소드* @param msg* / private static void broadcast (string msg) {if (msg.indexof ( "guest0")! = -1) {senduser (msg); } else {sendall (msg); }} / *** 모든 사용자에게 보내십시오* @param msg* / public static void sendall (string msg) {for (문자열 키 : connections.keyset ()) {chatannotation client = null; try {client = (chatannotation) connections.get (key); synchronized (client) {client.session.getBasicRemote (). SendText (MSG); }} catch (ioexception e) {log.debug ( "채팅 오류 : 클라이언트에 메시지를 보내지 못했습니다", e); Connections.remove (클라이언트); {client.session.close (); } catch (ioexception e1) {// incor} string message = string.format ( "* %s %s", client.nickname, "연결이 끊어졌습니다."); 방송 (메시지); }}} / *** 지정된 사용자에게 메시지를 보내십시오* @param msg* / public static void senduser (String Msg) {chatannotation c = (chatannotation) connections.get ( "guest0"); try {c.session.getBasicRemote (). SendText (msg); } catch (ioexception e) {log.debug ( "채팅 오류 : 클라이언트에 메시지를 보내지 못했습니다", e); 연결 (C); try {c.session.close (); } catch (ioexception e1) {// ingore} string message = string.format ( "* %s %s", c.nickname, "연결이 끊어졌습니다."); 방송 (메시지); }}}htmlfilter 도구 클래스 :
/*** html 도구 클래스** @author hu hansan*/public final class htmlfilter {public static string filter (문자열 메시지) {if (message == null) return (null); char content [] = new char [message.length ()]; message.getchars (0, message.length (), 내용, 0); StringBuilder result = new StringBuilder (content.length + 50); for (int i = 0; i <content.length; i ++) {switch (content [i]) {case '<': result.append ( "<"); 부서지다; CASE '>': result.Append ( ">"); 부서지다; CASE '&': result.Append ( "&"); 부서지다; CASE ' "': result.Append (" ""); 부서지다; 기본값 : result.Append (content [i]); }} return (result.toString ()); }}페이지:
<%@ page language = "java"import = "java.util.*"pageencoding = "utf-8"%> <%string path = request.getContextPath (); String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.1. 인코딩 = "utf-8"?> <html xmlns = "http://www.w3.org/1999/xhtml"xml : lang = "en"> <head> <title> test </title> <style type = "text/css"> 입력 #채팅 {410px} # } #console {테두리 : 1px solid #cccccc; 국경 오른쪽 색 : #99999; 국경-바닥 색 : #99999; 높이 : 170px; 오버플로-스크롤; 패딩 : 5px; 너비 : 100%; } #console p {패딩 : 0; 여백 : 0; } </style> <script type = "text/javaScript"> var chat = {}; chat.socket = null; chat.connect = (function (host) {if ( 'wind Console.log (webSocket Connection 닫는다. '); chat.initialize = function () {if (wind } else {chat.connect ( 'wss : //' + window.location.host.host + '/socket2/websocket/chat'); }}; chat.sendmessage = (function () {var message = document.getElementById ( 'chat'). value; if (message! = '') {chat.socket.send (message); docum var 콘솔 = {}; console.log = (function (messag } console.scrolltop = console.scrollheight}; chat.initialize (); document.adeventListener ( "domcontentLoaded", function () {// "noscript"클래스 - <noscript>가있는 요소를 제거합니다 xhtml var noscripts = document.getElementsByClassName ( "noscript"); for (var i = 0; i <noscriptts.length; i ++) { noscripts [i] .parentnode.removechild (noscripts [i]), false); </script> </head> <body> <div> <h2 style = "색상 : #ff0000"> 브라우저가 JavaScript를 지원하지 않는 것 같습니다! WebSockets는 JavaScript를 활성화하는 데 의존합니다. JavaScript 및 Reload this Page! </h2> </div> <div> <p> <입력 유형 = "text"placeholder = "컨텐츠를 입력하십시오"id = "Chat"/> </p> <div id = "Console-Container"> <div id = "Console"/> </div> </body> </html> 특정 사용자에게 보내도록 지정하거나 모든 것을 보낼 수 있습니다. 자세한 내용은 Chatannotation 클래스의 방송 방법을 참조하십시오.
프로그램을 게시 할 때 Tomcat-Coyote.jar, Tomcat-juli.jar 및 WebSocket-Api.jar의 세 가지 JAR 패키지를 삭제하고 Tomcat을 시작하십시오.
프로그램 스크린 샷, Guest0 사용자는 정보를 보내고 백그라운드에서 판단을하고 그 자체로만 보냅니다.
게스트 1 :
Guest2 :
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.