この記事では、参照用のチャットメッセージプッシュ機能を実装するために、Java WebSocketの特定のコードを共有しています。特定のコンテンツは次のとおりです
環境:
JDK.1.7.0_51
Apache-Tomcat-7.0.53
Java Jarパッケージ:Tomcat-Coyote.jar、tomcat-juli.jar、websocket-api.jar
Chatannotationメッセージの送信クラス:
java.io.ioexception; import java.util.hashmap; import java.util.map; import java.util.concurrent.atomic.atomicinteger; javax.websocket.onclose;インポートjavax.websocket.onerror;インポートjavax.websocket.onmessage; Import javax.websocket.onopen; import javax.websocket.session; Import javax.websocket.serverendpoint; Import org.ali.logging.log.log.log.log.loggging; org.apache.juli.logging.logfactory; com.util.htmlfilterをインポートします。 /*** WebSocket Message Push Service Class* @Author Hu Hansan** 2014-11-18 7:53:13 PM*/ @serverEndpoint(value = "/websocket/chat")public class chatannotation {private static final log = logactory.getlog(chatannotation.class); private static final string guest_prefix = "guest";プライベート静的最終AtomicInteger ConnectionIds = new AtomicInteger(0); private static final Map <string、object> connections = new Hashmap <String、object>();プライベートファイナルストリングニックネーム。プライベートセッションセッション。 public chatannotation(){nickname = guest_prefix + connectionIds.getandincrement(); } @onopen public void start(session session){this.session = session; connections.put(ニックネーム、これ); string message = string.format( "*%s%s"、nickname、 "が参加しました。");ブロードキャスト(メッセージ); } @onclose public void end(){connections.remove(this); string message = string.format( "*%s%s"、nickname、 "は切断されています。");ブロードキャスト(メッセージ); } / ***メッセージの送信トリガーメソッド* @paramメッセージ* / @onmessage public void encoming(string message){//クライアント文字列filteredmessage = string.format( "%s:%s"、nickname、htmlfilter.filter(message.tostring()));ブロードキャスト(FilteredMessage); } @onerror public void onerror(スロー可能なt)スロースロー可能{log.error( "チャットエラー:" + t.toString()、t); } / ***メッセージ送信方法* @param msg* / private static void broadcast(string msg){if(msg.indexof( "guest0")!= -1){senduser(msg); } else {sendall(msg); }} / ***すべてのユーザーに送信* @param msg* / public static void sendal(string msg){for(string key:connections.keyset()){chatannotation client = null; try {client =(chatannotation)connections.get(key);同期(client){client.session.getBasicRemote()。sendtext(msg); }} catch(ioException e){log.debug( "チャットエラー:クライアントにメッセージを送信できなかった"、e); connections.remove(クライアント); try {client.session.close(); } catch(ioexception e1){// adganore} 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); connections.remove(c); try {c.session.close(); } catch(ioexception e1){// adganore} string message = string.format( "*%s%s"、c.nickname、 "が切断されました。");ブロードキャスト(メッセージ); }}}htmlfilterツールクラス:
/*** HTMLツールクラス** @Author hu Hansan*/public final class htmlfilter {public static string filter(string message){if(message == null)return(null); char content [] = new char [message.length()]; message.getchars(0、message.length()、content、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( ">");壊す;ケース '&':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.getServerport( encoding = "UTF-8"? } #console {border:1px solid #cccccc;境界線 - 色:#99999; Border-Bottom-Color:#99999;高さ:170px;オーバーフロー-Y:スクロール;パディング:5px;幅:100%; } #Console P {PADDING:0;マージン:0; } </style> <script type = "text/javascript"> var chat = {}; chat.socket = null; chat.connect =(function(host){if( 'websocket' in window){chat.socket = new websocket(host);} else if( 'mozwebsocket' in window){chat.socket = new mozwebsocket(host);} else {console.log( 'error:errer:websocketはuntsucteer of this browser。 console.log(websockent document.getelementbyid( 'chat){event.keycode == 13)閉じている。}; chat.initialize = function(){if(window.location.protocol == 'http:'){chat.connect( 'ws://' + window.location.host + '/socket2/websocket/chat'); } else {chat.connect( 'wss://' + window.location.host + '/socket2/websocket/chat'); }}; chat.sendmessage =(function(){var message = document.getElementbyId( 'chat')。value; if(message!= ''){chat.socket.send(message); document.getElementbyId( 'chat')。value = '';}}); var Console = {}; console.log =(function(message){var console = document.getelementbyid( 'console'); var p = document.createelement( 'p'); p.style.wordwrap = 'break-word'; p.innerhtml = message; console.AppendChild(P); Console.RemoveChild(Console.FirstChild); chat.initialize(); document.addeventlistener( "domcontentloaded"、function(){// "noscript" class- <noscript>で要素を削除xhtml var noscripts = document.getelementsbyclassname( "noscript"); noscripts [i] .parentnode.RemoveChild(noscripts [i])}}}; </script> </head> <body> <div> <h2 style = "color:#ff0000">ブラウザがJavaScriptをサポートしていないようです。 WebSocketsは、有効になっているJavaScriptに依存しています。 JavaScriptを有効にしてこのページをリロードしてください!特定のユーザーに送信するように指定することも、すべてを送信することもできます。詳細については、ChatAnnotationクラスのブロードキャスト方法を参照してください。
プログラムを公開するときは、3つのJARパッケージを削除して、tomcat-coyote.jar、tomcat-juli.jar、およびwebsocket-api.jarを削除して、Tomcatを開始してください。
プログラムスクリーンショット、Guest0ユーザーは情報を送信し、バックグラウンドで判断を下し、それを自分自身に送信するだけです。
ゲスト1:
guest2:
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。