window环境使用C++实现WebSocket

本文介绍了在Windows环境下使用C++实现WebSocket服务器的过程。通过分析整体代码结构和关键步骤,包括握手请求与响应的处理,以及数据通信的加密与解密。文中详细解释了WebSocket的协议流程,并提供了相关代码示例。

最近因为项目需求,需要使用C++实现WebSocket与浏览器进行通讯,针对WebSocket有很多开源的框架,但是本人比较懒,所以干脆手写一个算了.

 https://download.csdn.net/download/weixin_34196559/10750141开源库

废话不说,直接上代码

1. 整体代码截图

全部代码,基本400行以内可以搞定

项目结构,因为实现WebSocket需要涉及到加密解密,所以从网上某大神哪里拿来了代码

以上是整体的代码结构, 下面我简单介绍下WebSocket的流程

先贴一张图 WebSocket的基本结构 想详细了解协议内容,看这位大神的博客 https://www.cnblogs.com/songwenjie/p/8575579.html

第一步 客户端首先发送握手请求(看下图, 他长这样), 在这里面最重要的就是那个Sec-WebSocket-Key 数值, 这玩意每次来都是随机,你需要对他按照固定方式加密然后返回给客户端, 多说一句,这请求头的意思打算把协议升级成WebSocket协议, 你要是同意就按照规矩加密数据传回来.

第二步 服务端返回握手响应给客户端(看下图, 他长这样)Sec-WebSocket-Accept: 就

HTML 5 Web Sockets is a powerful and effective technique for real-time information processing. There exists many techniques such as Poling, Long Poling and Streaming that are said to be better earier days. With web sockets, it shows a better outcome for the end user as well as a proper utilization of the server bandwidth. WebSocket is a web technology providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API for in Web IDL is being standardized by the W3C.WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket Protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request. The WebSocket protocol makes possible more interaction between a browser and a web site, facilitating live content and the creation of real-time games. This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for messages to be passed back and forth while keeping the connection open. In this way a two-way (bi-directional) ongoing conversation can take place between a browser and the server. A similar effect has been achieved in non-standardized ways using stop-gap technologies such as Comet.In addition, the communications are done over TCP port number 80, which is of benefit for those environments which block non-standard Internet connections using a firewall. WebSocket protocol is currently supported in several browsers including Google Chrome, Internet Explorer, Firefox, Safari and Opera. WebSocket also requires web applications on the server to support it. Here goes a comparison of polling vs Web Sockets.
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值