Ethereum websocket API
Ethereum specifies the JSON RPC API application development interface that each node needs to implement. This interface is transport independent. Applications can use this interface protocol to operate Ethereum nodes through HTTP, websocket or IPC and other communication mechanisms:
cocos2d-x engine integrates libwebsockets and encapsulates a layer of easy-to-use interface based on the client API of libwebsockets, so that the engine can easily use websocket for game network communication in C + +, JS and Lua layers
the article is very long. I'll give you a link:
[cocos2d-x tutorial] how to use websocket_ Network experience
http://jingyan..com/article/c33e3f48ae9158ea14cbb562.html
before the appearance of websocket, there were two ways to realize web real-time: polling mechanism and stream technology; There are different polling methods and a long polling method called comet
polling: This is the first solution to realize real-time web application. The client sends requests to the server at a certain time interval to keep the synchronization between the client and the server by frequent requests. The disadvantage of this synchronization scheme is that when the client requests the server with a fixed frequency, the data on the server may not be updated, which will bring a lot of unnecessary network transmission, so it is a very inefficient real-time scheme
long polling: it is an improvement of timed polling to rece invalid network transmission. When there is no data update on the server, the connection will be maintained for a period of time until the data or state changes or the time expires. This mechanism can rece the invalid interaction between the client and the server. Of course, if the data of the server changes very frequently, this mechanism has no essential performance improvement compared with the timed polling
stream: it is often a hidden window on the client page to send a long connection request to the server. After receiving the request, the server responds and constantly updates the connection status to ensure that the connection between the client and the server does not expire. Through this mechanism, the server-side information can be continuously pushed to the client. This mechanism has a problem in user experience. It needs to design different schemes for different browsers to improve user experience. At the same time, this mechanism is a great test for the server-side resources in the case of large concurrency
in fact, the above method is not a real real-time technology, but uses a technique to realize the real-time simulation. Each interaction between client and server is a process of HTTP request and response, and each HTTP request and response has complete HTTP header information, which increases the amount of data transmitted each time. But the most painful thing about these methods is the developers, because the implementation of both the client and the server is very complex. In order to simulate the real-time effect, developers often need to construct two HTTP connections to simulate the two-way communication between the client and the server. One connection is used to process the data transmission from the client to the server, A connection is used to process the data transmission from server to client, which inevitably increases the complexity of programming, increases the load of server, and restricts the scalability of the application system
based on the above disadvantages, the technology of realizing web real-time application appears. Websocket really realizes the real-time communication ability of desktop system under C / S architecture through the API provided by browser. Its principle is to use JavaScript to call the browser API to send a websocket request to the server. After a handshake, TCP communication is established with the server. Because it is essentially a TCP connection, the stability of data transmission is strong and the amount of data transmission is relatively small<
websocket protocol
websocket protocol is essentially a TCP based protocol. In order to establish a websocket connection, the client browser must first send an HTTP request to the server. This request is different from the normal HTTP request, and contains some additional header information. The additional header information "upgrade: websocket" indicates that this is an HTTP request for protocol upgrade, The server side parses these additional header information, and then generates a response message to return to the client side. The websocket connection between the client side and the server side is established, and both sides can freely transfer information through this connection channel, and the connection will continue until the client side or one of the server side actively closes the connection
let's introce the websocket protocol in detail. As the protocol is still in the draft stage and the version changes rapidly, we choose the latest draft-ietf-hibi-the websocket protocol-17 version to describe the websocket protocol. Because this version is currently well supported in some mainstream browsers, such as chrome, Firefox and opera. Through the description, we can see the content of handshake protocol
sent from client to server:
the code is as follows:
get / chat http / 1.1
host: server. Example. Com
upgrade: websocket
connection: upgrade
sec websocket key: dghlihnhbxbszsbub25jzq = =
origin:
sec websocket protocol: chat, Hyperchat
sec websocket version: 13
content from server to client:
the code as follows
http / 1.1 101 switching protocols
upgrade: websocket
connection: upgrade
sec websocket accept: s3pplmbitxaq9kygzzhzbk + Xoo =
sec websocket protocol: chat
these requests and the usual HTTP requests are They are very similar, but some of them are closely related to websocket protocol. We need to give a brief introction to these request and response information, "u said pgrade:WebSocket ”It means that this is a special HTTP request. The purpose of the request is to upgrade the communication protocol between client and server from HTTP protocol to websocket protocol. The SEC websocket key of the client and the SEC websocket accept of the server are important handshake authentication information. These contents will be explained in the blog post of the server implementation
I believe that through the above explanation, you should have a preliminary understanding of websocket. If you have any questions, you are welcome to communicate
client
as the handshake protocol described in the concept section, the client is provided by the browser API, so as long as you use JavaScript to simply call it, and the server is to implement it by itself, and the server will talk about it in the next blog< The code is as follows:
websocket JavaScript interface definition:
[constructor (in domstring URL, optional in domstring protocol)]
interface websocket {
readonly attribute domstring URL< br />// ready state
const unsigned short CONNECTING = 0;< br />const unsigned short OPEN = 1;< br />const unsigned short CLOSED = 2;< br />readonly attribute unsigned short readyState;< br />readonly attribute unsigned long bufferedAmount;< br />
// networking
attribute Function onopen;< br />attribute Function onmessage;< br />attribute Function onclose;< br />boolean send(in DOMString data);< br />void close();< br />};< br />WebSocket implements EventTarget; <
simply understand the interface methods and properties:
readyState indicates that the connection has four states:
connecting (0): indicates that the connection has not been established
Open (1): the connection has been established and can be used for communication
closing (2): closing the connection by closing the handshake
closed (3): the connection has been closed or cannot be opened
URL is the network address of websocket server. The protocol is usually "WS" or "WSS" (encrypted communication). The send method is to send data to the server
the close method is to close the connection
onopen connection establishment is the event triggered by successful handshake
event triggered when onmessage receives a server message
events triggered by onerror exception
onclose the event triggered by closing the connection
JavaScript invokes the browser interface as follows:
the code is as follows: the code
var wsserver = & 39; ws:// localhost:8888/Demo' ;; // Server address
var websocket = new websocket (wsserver)// Create websocket object
websocket. Send (& quot; hello");// Send a message to the server
alert (websocket. ReadyState)// View the current status of websocket
websocket. Onopen = function (EVT) {
/ / connection established
}
websocket. Onclose = function (EVT) {
/ / the connection has been closed
}
websocket.onmessage = function (EVT) {
/ / after receiving the server message, use evt.data to extract
}
websocket. Onerror = function (EVT) {
/ / exception
};
can rely on the following third-party implementation
WebKit
client
API implementation must be extracted from the source code by yourself,
qtwebkits
client / server
needs QT framework support
wt
client / server
relies on boost ASIO
< B R / > libwebsockets
client / server
belongs to C lib, which is easy to call and has clear documents. You can encapsulate C + + spec by yourself
there are many third-party implementations, and you can network by yourself
you can leave a message whenever you have any problem
First, turn the JSON string into a JSON object. The transformation is as follows:
< pre t = "code" L = "Java" > $. Parsejson (event. Data) Pre >provides you with two additional tools:
JSON online parsing: http://www.sojson.com/
JSON parsing: http://www.sojson.com/simple_ json.html
Alibaba cloud API gateway provides two-way communication capability. The official language of SDK is limited, and some languages need users to develop their own SDK
when the client calls the API, the request and response are strings in pure JSON format, that is, the HTTP request object is formatted and transmitted according to the JSON syntax. When websocket communicates, it will format the HTTP request message as a string format for transmission
in the process of two-way communication, in addition to the normal API call, there are a series of customized commands:
client registration: command word, command type, sender, format, etc
client keeps heartbeat:
import os
import struct
import base64
import hashlib
import socket
import threading
import paramiko
def get_ssh(ip, user, pwd):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, 22, user, pwd, timeout=15)
return ssh
except Exception, e:
print e
return "False"
def recv_data(conn): # 服务器解析浏览器发送的信息
try:
all_data = conn.recv(1024)
if not len(all_data):
return False
except:
pass
else:
code_len = ord(all_data[1]) & 127
if code_len == 126:
masks = all_data[4:8]
data = all_data[8:]
elif code_len == 127:
masks = all_data[10:14]
data = all_data[14:]
else:
masks = all_data[2:6]
data = all_data[6:]
raw_str = ""
i = 0
for d in data:
raw_str += chr(ord(d) ^ ord(masks[i % 4]))
i += 1
return raw_str
def send_data(conn, data): # 服务器处理发送给浏览器的信息
if data:
data = str(data)
else:
return False
token = "\x81"
length = len(data)
if length < 126:
token += struct.pack("B", length) # struct为Python中处理二进制数的模块,二进制流为C,或网络流的形式
elif length <= 0xFFFF:
token += struct.pack("!BH", 126, length)
else:
token += struct.pack("!BQ", 127, length)
data = '%s%s' % (token, data)
conn.send(data)
return True
def handshake(conn, address, thread_name):
headers = {}
shake = conn.recv(1024)
if not len(shake):
return False
print ('%s : Socket start handshaken with %s:%s' % (thread_name, address[0], address[1]))
header, data = shake.split('\r\n\r\n', 1)
for line in header.split('\r\n')[1:]:
key, value = line.split(': ', 1)
headers[key] = value
if 'Sec-WebSocket-Key' not in headers:
print ('%s : This socket is not websocket, client close.' % thread_name)
conn.close()
return False
MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
HANDSHAKE_STRING = "HTTP/1.1 101 Switching Protocols\r\n" \
"Upgrade:websocket\r\n" \
"Connection: Upgrade\r\n" \
"Sec-WebSocket-Accept: {1}\r\n" \
"WebSocket-Origin: {2}\r\n" \
"WebSocket-Location: ws://{3}/\r\n\r\n"
sec_key = headers['Sec-WebSocket-Key']
res_key = base64.b64encode(hashlib.sha1(sec_key + MAGIC_STRING).digest())
str_handshake = HANDSHAKE_STRING.replace('{1}', res_key).replace('{2}', headers['Origin']).replace('{3}', headers['Host'])
conn.send(str_handshake)
print ('%s : Socket handshaken with %s:%s success' % (thread_name, address[0], address[1]))
print 'Start transmitting data...'
print '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'
return True
def dojob(conn, address, thread_name):
handshake(conn, address, thread_name) # 握手
conn.setblocking(0) # 设置socket为非阻塞
ssh = get_ssh('192.168.1.1', 'root', '123456') # 连接远程服务器
ssh_t = ssh.get_transport()
chan = ssh_t.open_session()
chan.setblocking(0) # 设置非阻塞
chan.exec_command('tail -f /var/log/messages')
while True:
clientdata = recv_data(conn)
if clientdata is not None and 'quit' in clientdata: # 但浏览器点击stop按钮或close按钮时,断开连接
print ('%s : Socket close with %s:%s' % (thread_name, address[0], address[1]))
send_data(conn, 'close connect')
conn.close()
break
while True:
while chan.recv_ready():
clientdata1 = recv_data(conn)
if clientdata1 is not None and 'quit' in clientdata1:
print ('%s : Socket close with %s:%s' % (thread_name, address[0], address[1]))
send_data(conn, 'close connect')
conn.close()
break
log_msg = chan.recv(10000).strip() # 接收日志信息
print log_msg
send_data(conn, log_msg)
if chan.exit_status_ready():
break
clientdata2 = recv_data(conn)
if clientdata2 is not None and 'quit' in clientdata2:
print ('%s : Socket close with %s:%s' % (thread_name, address[0], address[1]))
send_data(conn, 'close connect')
conn.close()
break
break
def ws_service():
index = 1
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 12345))
sock.listen(100)
print ('\r\n\r\nWebsocket server start, wait for connect!')
print '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'
while True:
connection, address = sock.accept()
thread_name = 'thread_%s' % index
print ('%s : Connection from %s:%s' % (thread_name, address[0], address[1]))
t = threading.Thread(target=dojob, args=(connection, address, thread_name))
t.start()
index += 1
ws_service()
note:
the config objects of client and server can only be @ serverendpoint and @ clientendpoint annotation elements (such as value, encoder, decoder, configurator, etc.) equivalent to (programming) objects
1. Introction to websocket API
first of all, let's look at a simple JavaScript code, which calls the WebSockets API< br />
[javascript] view plain
var ws = new WebSocket(“ws://echo.websocket.org”);< br />
ws.onopen = function(){ws.send(“Test!”); };< br />
ws.onmessage = function(evt){console.log(evt.data); ws.close();};< br />
ws.onclose = function(evt){console.log(“WebSocketClosed!”);};< br />
ws.onerror = function(evt){console.log(“WebSocketError!”);};
there are only five lines in this code. Now let's give a brief overview of the meaning of these five lines of code
the first line of code is to apply for a websocket object. The parameter is the address of the server to be connected. The same as HTTP protocol, the URL of websocket protocol starts with WS / /, and the secure websocket protocol starts with WSS / /.