您的位置:首页 > 运维架构 > Tomcat

Tomcat7 搭建 websocket服务

2016-04-17 21:34 369 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java server tomcat