WebSocket.之.基礎入門-建立連接


 

WebSocket.之.基礎入門-建立連接

1. 使用開發工具(STS、Eclipse等)創建web項目。如下圖所示,啥東西都沒有。一個新的web項目。

 

 

2. 創建java類、index.jsp頁面。注意:web.xml未做任何改動.

TestConfig.java 代碼如下:

 1 package com.charles.socket;
 2 
 3 import java.util.Set;
 4 
 5 import javax.websocket.Endpoint;
 6 import javax.websocket.server.ServerApplicationConfig;
 7 import javax.websocket.server.ServerEndpointConfig;
 8 
 9 public class TestConfig implements ServerApplicationConfig{
10 
11     // 這個方法是使用注解進行開發
12     @Override
13     public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> arg0) {
14         // TODO 我們使用注解進行開發,簡單。
15         
16         // 這個方法中可以進行過濾篩選Socket,但我們現在什么都不操作,直接返回arg0 ,21行:return arg0
17         System.out.println("*******************************************");
18         System.out.println("WebSocket初始的個數:" + arg0.size());
19         System.out.println("*******************************************");
20         
21         return arg0;
22     }
23     
24     // 這個方法是使用配置文件進行開發
25     @Override
26     public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> arg0) {
27         // TODO Auto-generated method stub
28         return null;
29     }
30 }

 

TestSocket.java 代碼

package com.charles.socket;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/helloSocket")
public class TestSocket {

    /***
     * 當建立鏈接時,調用的方法.
     * @param session
     */
    @OnOpen
    public void open(Session session) {
        
        System.out.println("開始建立了鏈接...");
        System.out.println("當前session的id是:" + session.getId());
    }
}

 

 index.jsp 代碼

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Charles-WebSocket</title>

<script type="text/javascript">
    
    var websocket = null;
    var target = "ws://localhost:8080/websocket/helloSocket";
    
    function buildConnection() {
        
        if('WebSocket' in window) {
            websocket = new WebSocket(target);        
        } else if('MozWebSocket' in window) {
            websocket = MozWebSocket(target);
        } else {
            window.alert("瀏覽器不支持WebSocket");
        }
    }
    
</script>
</head>
<body>
    
    <button onclick="buildConnection();">開始建立鏈接</button>

</body>
</html>

 

 

將項目部署在Tomcat中進行運行,注意:Tomcat版本需要在7.x 以上。

 

由於項目中只寫了一個 WebSocket(TestSocket.java),所以在啟動的日志中,你能看到統計的socket僅有一個。

 

訪問瀏覽器:http://localhost:8080/websocket

 

在頁面上點擊按鈕:開始建立鏈接,看后台日志。如下圖所示,有后台日志打印出來,說明前端和后端,建立連接成功。

 

如有問題,歡迎糾正!!!

如有轉載,請標明源處:https://www.cnblogs.com/Charles-Yuan/p/9784349.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM