WebSocket is a communications protocol which provides a full-duplex communication channel over a single TCP connection. WebSocket protocol is standardized by the IETF as RFC 6455.
WebSocket and HTTP, both distinct and are located in layer 7 of the OSI model and depend on TCP at layer 4. RFC 6455 states that "WebSocket is designed to work over HTTP ports 80 and 443 as well as to support HTTP proxies and intermediaries", making it compatible with HTTP protocol. WebSocket handshake uses the HTTP Upgrade header to change from the HTTP to WebSocket protocol.
WebSocket protocol enables interaction between a web browser or any client application and a web server, facilitating the real-time data transfer from and to the server.
The below example is compatible with python3, and tries to connect to a web socket server.
以下示例与python3兼容,并尝试连接到Web套接字服务器。
Example 1: Short lived connection
示例1:短暂的连接
from websocket import create_connection def short_lived_connection(): ws = create_connection("ws://localhost:4040/") print("Sending 'Hello Server'...") ws.send("Hello, Server") print("Sent") print("Receiving...") result = ws.recv() print("Received '%s'" % result) ws.close() if __name__ == '__main__': short_lived_connection()
Output
输出量
Sending 'Hello, World'... Sent Receiving... Received 'hello world'
The short lived connection, is useful when the client doesn't have to keep the session alive for ever and is used to send the data only at a given instant.
import websocket def on_message(ws, message): ''' This method is invoked when ever the client receives any message from server ''' print("received message as {}".format(message)) ws.send("hello again") print("sending 'hello again'") def on_error(ws, error): ''' This method is invoked when there is an error in connectivity ''' print("received error as {}".format(error)) def on_close(ws): ''' This method is invoked when the connection between the client and server is closed ''' print("Connection closed") def on_open(ws): ''' This method is invoked as soon as the connection between client and server is opened and only for the first time ''' ws.send("hello there") print("sent message on open") if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://localhost:4040/", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()