In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces Go how to achieve WebSockets related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will have something to gain after reading this Go how to achieve WebSockets article, let's take a look.
What is WebSockets?
In short, WebSocket is a Web technology that enables two-way, full-duplex communication between the client and the server through a persistent single socket connection. WebSocket is for Web application developers to provide basically a close to the original TCP communication layer.
The WebSocket connection is initiated with an HTTP request / response handshake. If this initial handshake is successful, the client and server have agreed to use the existing TCP / IP connection established for the HTTP request as the WebSocket connection. As long as the WebSocket connection serves its purpose, it can be terminated by turning off the handshake, and both the client and the server can start.
WebSockets marks a turning point in Web development. Until the advent of WebSockets, real-time networks were difficult to implement and slow we are used to now; it is provided through the use of technologies such as Ajax and Comet (long) polling, which are not really optimized for real-time applications.
WebSocket technology has wide applicability. You can use it for different purposes, such as streaming data between back-end services, or connecting the front end through a long-term full-duplex connection. In short, WebSockets is an excellent choice for building event-driven systems and building real-time applications and services, where it must provide the data necessary for data anytime, anywhere.
We can roughly divide the WebSocket use cases into two different categories:
Real-time updates. The communication is one-way and the server streams low-latency (usually frequent) updates to the client. Think of live sports updates, alerts, real-time dashboards, or location tracking, just to name a few
Two-way communication. Both the client and the server send and receive messages. Examples include chat, virtual events, and virtual classrooms (the last two usually involve polling, quizzes, and Q&AS). WebSocket can also be used to support multi-user synchronous collaboration functions, such as multiple people editing the same document at the same time
Network socket and WebSockets
Network sockets, or sockets for short, are used as internal endpoints for exchanging data between applications running on the same computer or on different computers on the same network.
Sockets are a key part of Unix-and Windows-based operating systems that make it easier for developers to create web-enabled software. Application developers can include sockets in their programs instead of building network connections from scratch. Because network sockets are used in many network protocols (HTTP, FTP, and so on), you can use multiple sockets at the same time.
Sockets are created and used by a set of function calls defined by the socket's application programming interface (API).
There are several types of network sockets:
Datagram sockets (SOCK_DGRAM), also known as connectionless sockets, use user Datagram Protocol (UDP). Datagram sockets support two-way message flow and retain record boundaries.
Streaming sockets (SOCK_STREAM), also known as connection-oriented sockets, use Transmission Control Protocol (TCP), flow Control transfer Protocol (SCTP), or Datagram congestion Control Protocol (DCCP). These sockets provide two-way, reliable, orderly, and non-repetitive data flows with no recording boundaries.
Raw sockets (raw IP sockets) are usually available in routers and other network devices. These sockets are usually Datagram-oriented, although their exact characteristics depend on the interface provided by the protocol. Most applications do not use raw sockets. They are provided to support the development of new communication protocols and to provide access to more esoteric facilities of existing protocols.
Socket communication
Each network socket is identified by an address, which is a triple of transport protocol, IP address, and port number.
There are two main protocols for communication between hosts: TCP and UDP. Let's see how your application connects to TCP and UDP sockets.
Connect to TCP socket
To establish a TCP connection, the Go client uses the DialTCP function in the net package. DialTCP returns a TCPConn object. After the connection is established, the client and the server begin to exchange data: the client sends a request to the server through the TCPConn object, the server parses the request and sends the response, and the TCPConn object receives the response from the server.
This connection remains valid until the client or server closes it. The function to create a connection is as follows:
Client code:
/ / inittcpAddr, err: = net.ResolveTCPAddr (resolver, serverAddr) if err! = nil {/ / handle error} conn, err: = net.DialTCP (network, nil, tcpAddr) if err! = nil {/ / handle error} / / send message_, err = conn.Write ({message}) if err! = nil {/ / handle error} / / receive messagevar buf [{buffSize}] byte_, err: = conn.Read (buf [0:]) if err! = nil {/ / handle error}
Server code:
/ / inittcpAddr, err: = net.ResolveTCPAddr (resolver, serverAddr) if err! = nil {/ / handle error} listener, err: = net.ListenTCP ("tcp", tcpAddr) if err! = nil {/ / handle error} / / listen for an incoming connectionconn, err: = listener.Accept () if err! = nil {/ / handle error} / / send messageif _, err: = conn.Write ({message}) Err! = nil {/ / handle error} / / receive messagebuf: = make ([] byte, 512) n, err: = conn.Read (Buf [0:]) if err! = nil {/ / handle error}
Connect to UDP socket
Compared with TCP sockets, when using UDP sockets, the client only needs to send a Datagram to the server. There is no Accept function because the server does not need to accept connections and is just waiting for the Datagram to arrive.
Other TCP functions have UDP counterparts; just replace TCP with UDP in the above function.
Client:
/ / initraddr, err: = net.ResolveUDPAddr ("udp", address) if err! = nil {/ / handle error} conn, err: = net.DialUDP ("udp", nil, raddr) if err! = nil {/ / handle error}. / / send messagebuffer: = make ([] byte, maxBufferSize) n, addr, err: = conn.ReadFrom (buffer) if err! = nil {/ / handle error}. / / receive messagebuffer: = make ([] byte, maxBufferSize) n Err = conn.WriteTo (buffer [: n], addr) if err! = nil {/ / handle error}
Server:
/ / initudpAddr, err: = net.ResolveUDPAddr (resolver, serverAddr) if err! = nil {/ / handle error} conn, err: = net.ListenUDP ("udp", udpAddr) if err! = nil {/ / handle error}. / / send messagebuffer: = make ([] byte, maxBufferSize) n, addr, err: = conn.ReadFromUDP (buffer) if err! = nil {/ / handle error}. / / receive messagebuffer: = make ([] byte, maxBufferSize) n, err = conn.WriteToUDP (buffer [: n] Addr) if err! = nil {/ / handle error} Summary
WebSocket communication packets provide a full-duplex communication channel over a single TCP connection. This means that both the client and the server can send data at the same time without any request.
WebSockets is a good solution for services that require continuous data exchange, such as instant messaging, online games and real-time trading systems. You can find complete information about the WebSocket protocol in the Internet Engineering Task Force (IETF) RFC 6455 specification.
The WebSocket connection is requested by the browser and responded by the server, and then the connection is established. This process is often called a handshake. A special type of header in WebSockets requires only a handshake between the browser and the server to establish a connection that remains active during its life cycle.
The WebSocket protocol uses port 80 for insecure connections and port 443 for secure connections. The WebSocket specification determines which uniform resource identifier schemes are required for ws (WebSocket) and wss (WebSocket Secure) protocols.
This is what the client request looks like:
GET / chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==Sec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13Origin: http://example.com
This is the server response:
HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=Sec-WebSocket-Protocol: chat
WebSockets solves many difficulties in developing real-time Web applications and has the following advantages over traditional HTTP:
Lightweight headers reduce data transmission overhead.
A single Web client requires only one TCP connection.
The WebSocket server can push data to the Web client.
The WebSocket protocol is relatively simple to implement. It uses the HTTP protocol for the initial handshake. After a successful handshake, a connection is established, and WebSocket essentially reads / writes data using the original TCP.
This is the end of the article on "how to achieve WebSockets in Go". Thank you for reading! I believe you all have a certain understanding of "how to achieve WebSockets in Go". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.