`

WebSocket

 
阅读更多

WebSocket是什么?

WebSocket是一种在单个TCP连接上进行全双向通信的协议。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。
在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
Websocket 通过HTTP/1.1 协议的101状态码进行握手。

 

握手

在客户端,new WebSocket实例化一个新的WebSocket客户端对象,请求类似 ws://yourdomain:port/path 的服务端WebSocket URL,客户端WebSocket对象会自动解析并识别为WebSocket请求,并连接服务端端口,执行双方握手过程,客户端发送数据格式类似:

可以看到,客户端发起的WebSocket连接报文类似传统HTTP报文,Upgrade:websocket参数值表明这是WebSocket类型请求,Sec-WebSocket-Key是WebSocket客户端发送的一个 base64编码的密文,要求服务端必须返回一个对应加密的Sec-WebSocket-Accept应答,否则客户端会抛出Error during WebSocket handshake错误,并关闭连接。

服务端收到报文后返回的数据格式类似:

 Sec-WebSocket-Accept的值是服务端采用与客户端一致的密钥计算出来后返回客户端的,HTTP/1.1 101 Switching Protocols表示服务端接受WebSocket协议的客户端连接,经过这样的请求-响应处理后,两端的WebSocket连接握手成功, 后续就可以进行TCP通讯了。

 

保持长连接

服务器和客户端通过发送Ping/Pong+Frame(RFC+6455+-+The+WebSocket+Protocol)。这种 Frame+是一种特殊的数据包,它只包含一些元数据而不需要真正的 Data+Payload,可以在不影响应用的情况下维持住中间网络的连接状态。

 

例子1

 

pom文件:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>1.3.5.RELEASE</version>
</dependency>

 

java:

package com.test;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketController {
    //当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。
    private static CopyOnWriteArraySet<WebSocketController> webSocketSet = new CopyOnWriteArraySet<WebSocketController>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);//加入set中
        addOnlineCount();//在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            sendMessage("init success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);//从set中删除
        subOnlineCount();//在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        try {
            session.getBasicRemote().sendText("service:"+message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误时调用
     */
     @OnError
     public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
     }

    /**
     * 发送消息
     */
     public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
     }

     /**
      * 群发自定义消息
      */
    public static void sendInfo(String message) {
        if(webSocketSet!=null && webSocketSet.size()>0) {
            for (WebSocketController item : webSocketSet) {
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketController.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketController.onlineCount--;
    }
}

 

package com.test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

 

html:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>

<body>
    Welcome Use WebSocket<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/websocket");
    } else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event){
        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>

 

 

例子2(一个websocket分发多个功能,通过参数区分)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>1.3.5.RELEASE</version>
</dependency>

 

package com.cuc.happyseat.config.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * 开启WebSocket支持
 */
@Configuration  
public class WebSocketConfig {  
    
    @Bean  
    public ServerEndpointExporter serverEndpointExporter() {  
        return new ServerEndpointExporter();  
    }  
  
}

 

WebSocket服务类对照下面的代码看:

第20行,@ServerEndpoint("/websocket/{userID}"),括号中的内容就是客户端请求Socket连接时的访问路径,userID是我要求客户端传来的参数,我这里算是为了标识该客户端吧。
第28行,在该类中添加属性 userID,并添加对应的getUserID()方法。
第46行,在onOpen()方法即建立连接的时候就接收参数userID,需要标识@PathParam("userID") 。接收参数后直接赋值给属性userID。
第140-157行,是针对特定客户端发送消息。服务器和客户端在建立连接成功后就生成了一个WebSocket对象,并存在集合中,对象里特有的属性是我们设置的userID。所以通过唯一的userID就能标识服务器与该客户端建立的那个连接啦!这样要求发送消息时,传入userID与消息,服务器在自己的WebSocket连接集合中遍历找到对应客户端的连接,就可以直接发消息过去啦~~

package com.cuc.happyseat.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

/*@ServerEndpoint注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
@ServerEndpoint("/websocket/{userID}")
@Component
public class WebSocketServer {

	//每个客户端都会有相应的session,服务端可以发送相关消息
	private Session session;

	//接收userID
	private Integer userID;
 
	//J.U.C包下线程安全的类,主要用来存放每个客户端对应的webSocket连接
	private static CopyOnWriteArraySet<WebSocketServer> copyOnWriteArraySet = new CopyOnWriteArraySet<WebSocketServer>();

	public Integer getUserID() {
		return userID;
	}
    
	/**
	 * @Name:onOpen
	 * @Description:打开连接。进入页面后会自动发请求到此进行连接
	 * @Author:mYunYu
	 * @Create Date:14:46 2018/11/15
	 * @Parameters:@PathParam("userID") Integer userID
	 * @Return:
	 */
	@OnOpen
	public void onOpen(Session session, @PathParam("userID") Integer userID) {
		this.session = session;
		this.userID = userID;
		System.out.println(this.session.getId());
		copyOnWriteArraySet.add(this);
	}

	/**
	 * @Name:onClose
	 * @Description:用户关闭页面,即关闭连接
	 * @Author:mYunYu
	 * @Create Date:14:46 2018/11/15
	 * @Parameters:
	 * @Return:
	 */
	@OnClose
	public void onClose() {
		copyOnWriteArraySet.remove(this);
	}

	/**
	 * @Name:onMessage
	 * @Description:测试客户端发送消息,测试是否联通
	 * @Author:mYunYu
	 * @Create Date:14:46 2018/11/15
	 * @Parameters:
	 * @Return:
	 */
	@OnMessage
	public void onMessage(String message) {
		System.out.println("websocket收到客户端发来的消息:"+message);
	}

	/**
	 * @Name:onError
	 * @Description:出现错误
	 * @Author:mYunYu
	 * @Create Date:14:46 2018/11/15
	 * @Parameters:
	 * @Return:
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("发生错误:" + error.getMessage() + "; sessionId:" + session.getId());
		error.printStackTrace();
	}

	public void sendMessage(Object object){
		//遍历客户端
		for (WebSocketServer webSocket : copyOnWriteArraySet) {
			System.out.println("websocket广播消息:" + object.toString());
			try {
				//服务器主动推送
				webSocket.session.getBasicRemote().sendObject(object) ;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @Name:sendMessage
	 * @Description:用于发送给客户端消息(群发)
	 * @Author:mYunYu
	 * @Create Date:14:46 2018/11/15
	 * @Parameters:
	 * @Return:
	 */
	public void sendMessage(String message) {
		//遍历客户端
		for (WebSocketServer webSocket : copyOnWriteArraySet) {
			System.out.println("websocket广播消息:" + message);
			try {
				//服务器主动推送
				webSocket.session.getBasicRemote().sendText(message);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @throws Exception 
	 * @Name:sendMessage
	 * @Description:用于发送给指定客户端消息
	 * @Author:mYunYu
	 * @Create Date:14:47 2018/11/15
	 * @Parameters:
	 * @Return:
	 */
	public void sendMessage(Integer userID, String message) throws Exception {
		Session session = null;
		WebSocketServer tempWebSocket = null;
		for (WebSocketServer webSocket : copyOnWriteArraySet) {
			if (webSocket.getUserID() == userID) {
				tempWebSocket = webSocket;
				session = webSocket.session;
				break;
			}
		}
		if (session != null) {
			//服务器主动推送
			tempWebSocket.session.getBasicRemote().sendText(message);
		} else {
			System.out.println("没有找到你指定ID的会话:{}"+ "; userId:" + userID);
		}
	}    
}

 

  • 大小: 42.6 KB
  • 大小: 30.4 KB
分享到:
评论

相关推荐

    C#实现WebSocket协议客户端和服务器websocket sharp组件实例解析

    WebSocket Sharp 是一个C#实现的WebSocket协议库,它支持客户端和服务端的功能,符合RFC 6455标准。这个组件不仅提供了基本的WebSocket连接管理,还包含了一些高级特性,如消息压缩、安全连接、HTTP身份验证、代理...

    MFC websocket server | MFC websocket服务器

    WebSocket是一种在客户端和服务器之间建立持久连接的网络协议,它允许双方进行全双工通信,即数据可以在两个方向上同时传输。MFC(Microsoft Foundation Classes)是微软提供的一套C++类库,用于构建Windows应用程序...

    DelphiWebsockets-master.zip_delphi websocket_websocket_websocket

    在Delphi编程环境中,WebSocket技术可以极大地提升应用程序的交互性和实时性,尤其是在开发需要实时数据更新的桌面或移动应用时。 DelphiWebsockets-master.zip是一个包含Delphi WebSocket实现的项目资源压缩包。这...

    若依WebSocket集成

    WebSocket是一种在客户端和服务器之间建立长连接的协议,它允许双方进行全双工通信,即数据可以在两个方向上同时传输,极大地提高了实时性。在若依框架中集成WebSocket,可以为用户带来更流畅、即时的交互体验,尤其...

    WebSocket消息实时提醒

    WebSocket是一种在客户端和服务器之间建立持久连接的网络协议,它为双向通信提供了低延迟、高效率的解决方案。在传统的HTTP协议下,客户端与服务器之间的通信是请求-响应模式,即客户端发起请求,服务器响应,然后...

    html页面测试websocket

    WebSocket是Web应用中一种在客户端和服务器之间建立长连接的协议,它允许双方进行全双工通信,极大地提高了数据传输效率。在这个“html页面测试websocket”的项目中,我们可以看到几个关键文件:`index.html`、`...

    websocket断线重连 websocket JS框架

    WebSocket是一种在客户端和服务器之间建立持久连接的协议,它允许双方进行全双工通信,即数据可以在两个方向上同时传输,极大地提高了实时性。在Web应用中,WebSocket为开发者提供了实时交互的能力,常用于在线聊天...

    C语言实现的websocket

    WebSocket是一种在客户端和服务器之间建立持久连接的网络通信协议,它允许双向通信,即服务器和客户端都可以主动发送数据。在Web开发中,WebSocket为实时应用提供了高效、低延迟的解决方案,比如在线聊天、股票交易...

    简单实现了websocket功能:websocket客户端、winformsocket客户端

    WebSocket是一种在客户端与服务器之间建立持久连接的协议,它允许双方进行全双工通信,即数据可以在两个方向上同时传输,极大地提高了实时性。在本项目中,"简单实现了websocket功能:websocket客户端、winform...

    Spring+Netty+WebSocket实例

    在现代Web开发中,实时通信已经成为一个不可或缺的功能,Spring、Netty和WebSocket的结合为构建高性能、低延迟的实时应用提供了强大的解决方案。本实例将详细探讨如何利用这三种技术进行集成,实现高效的双向通信。 ...

    websocket-sharp 范例

    WebSocketSharp是一个针对C#开发的开源库,它允许开发者在.NET Framework 4.0和3.5环境下构建WebSocket服务和客户端。WebSocket协议是一种在互联网上实时通信(RTC)的技术,它提供了一种低延迟、全双工的通信机制,...

    ubuntu lighttpd实现websocket

    1、下载mongoose使用mongoose中的example中的websocket_chat,实现websocket 2、websocket_chat源码下载路径 官网:https://cesanta.com 论坛:https://forum.mongoose-os.com/index.php?p=/categories/mongoose ...

    spring+websocketdemo

    WebSocket是Web交互技术的一种革新,它为实时双向通信提供了标准协议。在传统的HTTP协议中,客户端与服务器之间的通信是请求-响应模式,而WebSocket则允许持久连接,使得数据可以双向实时传输,极大地优化了实时应用...

    c# winform快速建websocket服务器源码 wpf快速搭建websocket服务

    c# winform快速建websocket服务器源码 wpf快速搭建websocket服务 c#简单建立websocket服务 websocket快速搭建 随着互联网技术的飞速发展,实时交互和数据推送已成为众多应用的核心需求。传统的HTTP协议,基于请求-...

    MFC实现WebSocket通信

    WebSocket是一种在客户端和服务器之间建立持久连接的网络通信协议,它允许双向实时数据传输,极大地提高了Web应用的性能。在本项目中,我们将利用Microsoft Foundation Classes (MFC) 框架,用C++编程语言在Visual ...

    websocket聊天室,学习websocket的好例子。

    WebSocket是Web交互技术的一种,它允许在客户端和服务器之间建立持久的、低延迟的双向连接。这个技术在2011年被W3C标准化,为实时应用如在线游戏、股票交易、聊天室等提供了高效的数据传输方式。WebSocket API设计得...

    websocket++库

    WebSocket++库是一个开源的C++库,专门用于实现WebSocket协议,该协议允许在Web浏览器和其他服务器之间进行全双工通信。WebSocket++库的设计目标是提供一个轻量级、高效且易于使用的WebSocket客户端和服务器实现,它...

    websocket与易语言通讯(源码)

    在易语言中实现WebSocket通讯,可以极大地提升网络应用的交互性,特别是对于需要实时更新数据的场景,如在线游戏、股票行情、聊天室等。 易语言是一门以中文编程为特色的编程语言,它以简洁直观的语法设计,使得...

    weblogic websocket示例代码

    WebSocket是Web交互技术的一种,它允许在客户端和服务器之间建立持久的、低延迟的双向通信。WebLogic Server作为Oracle提供的企业级Java应用服务器,支持WebSocket协议,为开发者提供了在Java EE环境中实现WebSocket...

    vue封装websocket.zip

    在现代Web应用中,实时通信是不可或缺的功能之一,WebSocket则提供了双向通信的能力,使得服务器与客户端能实时交换数据。在Vue项目中,对WebSocket进行封装能够提高代码的可维护性和重用性。 首先,让我们深入理解...

Global site tag (gtag.js) - Google Analytics