介紹MyEclipse整合Tomcat7,並開發WebSocket的全過程

來源:互聯網
上載者:User

標籤:

1.首先使MyEclipse8.6整合Tomcat7

注意配置參數

注意jar包

主機JDK版本

2.開發WebSocket

匯入websocket-api.jar

開發java檔案

package com.chen.websocket;import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/websocket")public class MyWebSocket {    private static int onlineCount = 0;         private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();         private Session session;    @OnOpen    public void onOpen(Session session){        this.session = session;        webSocketSet.add(this);            addOnlineCount();                   System.out.println("aaa?" + getOnlineCount());    }         @OnClose    public void onClose(){        webSocketSet.remove(this);          subOnlineCount();                       System.out.println("bbbb?" + getOnlineCount());    }          @OnMessage    public void onMessage(String message, Session session) {        System.out.println("ttt" + message);                 for(MyWebSocket item: webSocketSet){                         try {                item.sendMessage(message);            } catch (IOException e) {                e.printStackTrace();                continue;            }        }    }    @OnError    public void onError(Session session, Throwable error){        System.out.println("yy");        error.printStackTrace();    }         public void sendMessage(String message) throws IOException{        this.session.getBasicRemote().sendText(message);        //this.session.getAsyncRemote().sendText(message);    }     public static synchronized int getOnlineCount() {        return onlineCount;    }     public static synchronized void addOnlineCount() {        MyWebSocket.onlineCount++;    }         public static synchronized void subOnlineCount() {        MyWebSocket.onlineCount--;    }}
開發JSP
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%> <!DOCTYPE HTML><html>  <head>    <base href="<%=basePath%>">    <title>My WebSocket</title>  </head>     <body>    Welcome<br/>    <input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>    <div id="message">    </div>  </body>     <script type="text/javascript">      var websocket = null;             //判斷當前瀏覽器是否支援WebSocket      if(‘WebSocket‘ in window){          websocket = new WebSocket("ws://localhost:8080/MyWebSocket/websocket");      }      else{          alert(‘Not support websocket‘)      }             //串連發生錯誤的回調方法      websocket.onerror = function(){          setMessageInnerHTML("error");      };             //串連成功建立的回調方法      websocket.onopen = function(event){          setMessageInnerHTML("open");      }             //接收到訊息的回調方法      websocket.onmessage = function(){          setMessageInnerHTML(event.data);      }             //串連關閉的回調方法      websocket.onclose = function(){          setMessageInnerHTML("close");      }             //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket串連,防止串連還沒斷開就關閉視窗,server端會拋異常。      window.onbeforeunload = function(){          websocket.close();      }             //將訊息顯示在網頁上      function setMessageInnerHTML(innerHTML){          document.getElementById(‘message‘).innerHTML += innerHTML + ‘<br/>‘;      }             //關閉串連      function closeWebSocket(){          websocket.close();      }             //發送訊息      function send(){          var message = document.getElementById(‘text‘).value;          websocket.send(message);      }  </script></html>


3.部署

 

部署完之後需要在部署檔案下刪除websocket-api.jar,因為tomcat7已經有

 

4.運行項目








 

 

介紹MyEclipse整合Tomcat7,並開發WebSocket的全過程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.