標籤:java tomcat7 websocket server
pom.xml (雖然配置了maven tomcat7外掛程式,但是直接從maven中啟動web服務,websocket服務啟動不了。要將web服務部署到tomcat7 server上。可以直接打包war,也可以在開發工具中引入tomcat7)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>web</groupId> <artifactId>web</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>web Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>web</finalName> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.1</version> <configuration> <port>8077</port> <path>/web</path> <uriEncoding>UTF-8</uriEncoding> <finalName>web</finalName> <server>tomcat7</server> </configuration> </plugin> </plugins> </build></project>
websocket.server.SimpleServer
package websocket.server;import javax.websocket.*;import javax.websocket.server.ServerEndpoint;import java.io.IOException;import java.util.logging.Logger;/** * Created by Administrator on 2016/4/17. */@ServerEndpoint("/SimpleWebSocket")public class SimpleServer { private Logger logger = Logger.getLogger(this.getClass().getName()); @OnOpen public void onOpen(Session session){ logger.info("websocket open ... "); System.out.println(session); } /** * 串連關閉調用的方法 */ @OnClose public void onClose(){ logger.info("websocket close .... "); } @OnError public void onError(Throwable e){ logger.severe("error~~~~"+e.getMessage()); } /** * 收到用戶端訊息後調用的方法 * @param message 用戶端發送過來的訊息 * @param session 可選的參數 */ @OnMessage public void onMessage(String message, Session session) throws IOException { logger.info("receive the message from client ["+message+"]"); session.getBasicRemote().sendText("伺服器收到用戶端的資訊:"+message); }}
simple.html
<!DOCTYPE html><html><head> <title>Testing websockets</title></head><body> <input type="text" id="input"/> <input type="button" id="button" value="send"/><script type="text/javascript"> var webSocket = new WebSocket(‘ws://localhost:8077/web/SimpleWebSocket‘); webSocket.onerror = function(event) { console.log("error ... "); console.log(event.data); }; webSocket.onopen = function(event) { console.log("open ... "); console.log(event.data) }; webSocket.onmessage = function(event) { console.log("[message]:"+event.data); }; var btn = document.getElementById("button"); var input = document.getElementById("input"); btn.onclick = function(){ var value = input.value; webSocket.send(value); input.value=""; };</script></body></html>
Tomcat7 搭建 websocket服務