利用webSocket使網頁和伺服器通訊,websocket通訊

來源:互聯網
上載者:User

利用webSocket使網頁和伺服器通訊,websocket通訊

WebSocket protocol 是HTML5一種新的協議。它實現了瀏覽器與伺服器全雙工系統通訊(full-duplex)。具體說明請查閱相關資料,下面我來示範一種簡單的頁面與伺服器通訊的簡單範例。

建立個web工程(基於tomcat-7版本(6以下的版本未實現webSocket功能))

引入tomcat/lib目錄下的tomcat7-websocket.jar和websocket-api.jar添加到classpath中

建立WebSocketConfig.java如下

本次採用註解方式

import java.util.Set;import javax.websocket.Endpoint;import javax.websocket.server.ServerApplicationConfig;import javax.websocket.server.ServerEndpointConfig;public class WebSocketConfig implements ServerApplicationConfig{    @Override    public Set<ServerEndpointConfig> getEndpointConfigs(            Set<Class<? extends Endpoint>> scanned) {        return null;    }    @Override    public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {        //返回scanned        return scanned;    }}

編寫EchoSocket代碼

import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;@ServerEndpoint("/zqq/echo")public class EchoSocket {        public EchoSocket() {        super();    }    @OnOpen    public void open(Session session){        System.out.println("id " + session.getId());    }        @OnMessage    public void message(Session session,String msg){        System.out.println("sessionid " + session.getId() + " : " + msg);    }}

此時編寫用戶端echo.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'open.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--    <link rel="stylesheet" type="text/css" href="styles.css">    --><script type="text/javascript">    var ws;
  //websocket,協議開頭為ws var target = "ws://${pageContext.request.remoteHost}:8080${pageContext.request.contextPath}/zqq/echo"; function subOpen() { if ('WebSocket' in window) { ws = new WebSocket(target); } else if ('MozWebSocket' in window) { ws = new MozWebSocket(target); } else { alert('WebSocket is not supported by this browser.'); return; } ws.onmessage=function(event){ console.info(event.data); console.info(document.getElementById("h1").value); document.getElementById("h1").innerHTML+=event.data+" "; }; } function subSend(){ var text = document.getElementById("input").value; //alert(text); ws.send(text); document.getElementById("input").value=""; }</script></head><body> <button onclick="subOpen()">點擊開啟</button><br/> <input id="input"><br/> <button onclick="subSend()">發送</button></body></html>

此時將程式部署到tomcat上就可以訪問了,記得要先開啟通道,輸入文字就行

第一次寫東西,如有錯誤還請指教,繼續學習中。。。。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.