在centos上安装部署python websocket
时间: 2023-12-23 08:03:13 浏览: 273
1. 安装Python
首先,需要安装Python。如果已经安装了Python,请跳过此步骤。在CentOS上安装Python可以使用以下命令:
```
sudo yum install python3
```
2. 安装pip
pip是Python的包管理器,用于安装和管理Python包。在CentOS上安装pip可以使用以下命令:
```
sudo yum install epel-release
sudo yum install python-pip
```
3. 安装websocket库
使用pip安装websocket库:
```
pip install websocket
```
4. 编写websocket服务端代码
在Python中,使用`websocket`模块来创建websocket服务端。以下是一个简单的websocket服务端代码示例:
```
import websocket
def on_message(ws, message):
print("Received: ", message)
def on_error(ws, error):
print("Error: ", error)
def on_close(ws):
print("Closed")
def on_open(ws):
print("Opened")
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:8000/",
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()
```
这个简单的代码会创建一个websocket连接,并在接收到消息时打印出来。
5. 运行websocket服务端
在终端中运行websocket服务端代码:
```
python websocket_server.py
```
这将创建一个websocket连接并等待客户端连接。如果一切正常,你应该能够看到类似以下输出:
```
--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:8000
Origin: http://localhost:8000
Sec-WebSocket-Key: koxwGJfZ7LlTjT9o9dGc+g==
Sec-WebSocket-Version: 13
-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 1dQ2wgt/fnBjGtwTzXAfqRxjvUo=
-----------------------
Opened
```
6. 编写websocket客户端代码
在Python中,使用`websocket`模块来创建websocket客户端。以下是一个简单的websocket客户端代码示例:
```
import websocket
def on_message(ws, message):
print("Received: ", message)
def on_error(ws, error):
print("Error: ", error)
def on_close(ws):
print("Closed")
def on_open(ws):
print("Opened")
ws.send("Hello, World!")
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:8000/",
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()
```
这个简单的代码会创建一个websocket连接,并在连接打开时向服务端发送一条消息。
7. 运行websocket客户端
在终端中运行websocket客户端代码:
```
python websocket_client.py
```
这将创建一个websocket连接并向服务端发送一条消息。如果一切正常,你应该能够看到类似以下输出:
```
--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:8000
Origin: http://localhost:8000
Sec-WebSocket-Key: y+6GjJ7VuiFh+JW8XvU6Ag==
Sec-WebSocket-Version: 13
-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: G4g4dT4Zm1V0I4F0f9QzS1gYt+M=
-----------------------
Opened
send: b'Hello, World!'
Received: Hello, World!
Closed
```
阅读全文