js和python通过websocket通信
时间: 2023-11-18 08:10:22 浏览: 38
可以使用Python的WebSocket库(如websocket-client)和JavaScript的WebSocket API来实现WebSocket通信。
Python端示例代码:
```python
import websocket
import threading
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("Connection closed")
def on_open(ws):
def run(*args):
while True:
ws.send("Hello, World!")
time.sleep(1)
threading.Thread(target=run).start()
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:8000/ws/",
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()
```
JavaScript端示例代码:
```javascript
const ws = new WebSocket('ws://localhost:8000/ws/');
ws.onopen = function(event) {
console.log('WebSocket is open now.');
};
ws.onmessage = function(event) {
console.log('Received: ' + event.data);
};
ws.onerror = function(event) {
console.log('WebSocket error: ' + event.data);
};
ws.onclose = function(event) {
console.log('WebSocket is closed now.');
};
```
在上面的示例代码中,我们假设WebSocket服务器运行在本地主机上,且端口号为8000。你需要根据实际情况修改代码中的URL和端口号。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)