首先,需要服务器Jetty. 因为现在Tomcat并不支持Websocket
解压好服务器Jetty后,在命令行(cmd)(Jetty当前目录)中运行Java –jar start.jar既可
编写服务器代码:
创建类:WebSearchServlet.java
public class WebSearchServlet extends WebSocketServlet{
private static final long serialVersionUID = 5136484809757218548L;
public WebSocket doWebSocketConnect(HttpServletRequest request, String arg1) {
return new SearchServlet();
}
}
创建类:SearchServlet.java
public class SearchServlet implements WebSocket{
public SearchServlet(){
}
public void onClose(int arg0, String arg1) {
System.out.println("onClose");
}
public void onOpen(final Connection conn) {
new Thread() {
@Override
public void run() {
try {
while (true) {
sleep(1000);
conn.sendMessage("Count");
}
} catch (final Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
Web.xml代码
<servlet>
<servlet-name>WebSocket</servlet-name>
<servlet-class>org.search.servlet.WebSearchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WebSocket</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
HTML代码:
<script>
function websocket(x,y) {
var ws = new WebSocket("ws://16.187.87.35:8080/html5service/comet.do?x="+x+"&y="+y);
ws.onmessage = function(evt) {
console.log("evt.data:"+evt.data);
};
ws.onclose = function() {
};
ws.onopen = function() {
ws.send(x+","+y);
};
};
$(function(){
Websocket("1","2");
});
</script>