我尝试了'简单的websocket服务器' https://github.com/dpallot/simple-websocket-server
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
clients = []
class SimpleChat(WebSocket):
def handleMessage(self):
for client in clients:
if client != self:
client.sendMessage(self.data)
#client.sendMessage(self.address[0] + u' - ' + self.data)
def handleConnected(self):
print(self.address, 'connected')
print(self.request)
for client in clients:
client.sendMessage(self.address[0] + u' - connected')
clients.append(self)
def handleClose(self):
clients.remove(self)
print(self.address, 'closed')
for client in clients:
client.sendMessage(self.address[0] + u' - disconnected')
server = SimpleWebSocketServer('', 5000, SimpleChat)
server.serveforever()
我正在使用Wemos D1用于arduino板。下面是代码。 https://github.com/morrissinger/ESP8266-Websocket/blob/master/examples/WebSocketClient_Demo/WebSocketClient_Demo.ino
#include <ESP8266WiFi.h>
#include <WebSocketClient.h>
const char* arduino_id = "00000000"; // I gave the board an id
const char* ssid = "SSID";
const char* password = "password";
char path[] = "/";
char host[] = "10.1.1.61";
WebSocketClient webSocketClient;
// Use WiFiClient class to create TCP connections
WiFiClient client;
void setup()
{
Serial.begin(230400);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Connect to the websocket server
if (client.connect(host, 5000))
{
Serial.println("Connected to server");
}
else
{
Serial.println("Connection failed.");
}
// Handshake with the server
webSocketClient.path = path;
webSocketClient.host = host;
if (webSocketClient.handshake(client))
{
Serial.println("Handshake successful");
} else
{
Serial.println("Handshake failed.");
}
}
void loop()
{
Serial.println("got in to loop");
String data;
if (client.connected())
{
webSocketClient.getData(data);
if (data.length() > 0)
{
Serial.print("Received data: ");
Serial.println(data);
}
// capture the value of analog 1, send it along
//pinMode(1, INPUT);
//data = "kimchi";
//webSocketClient.sendData(data);
}
else
{
Serial.println("Client disconnected.");
}
// wait to fully let the client disconnect
delay(3000);
}
它正在发挥作用。
问题是arduino客户端无法在下面的flask websocketIO中工作。 它说“握手失败” (当我将服务器从'simpleWebServer'替换为'flask-SocketIO服务器'时,会弹出错误消息)
from flask import Flask, render_template, request
from flask_socketio import SocketIO
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
from flask_socketio import send, emit
@app.route("/")
def sayHi():
print(request.headers)
return "hi browser"
@app.route('/index')
def index():
return render_template('index.html', async_mode=socketio.async_mode)
@socketio.on('message')
def handle_message(message):
send(message)
@socketio.on('json')
def handle_json(json):
send(json, json=True)
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', json)
@socketio.on('connect')
def test_connect():
print('Client connected')
emit('my response', {'data': 'Connected'})
@socketio.on('disconnect')
def test_disconnect():
print('Client disconnected')
@socketio.on_error()
def chat_error_handler(e):
print('An error has occurred: ' + str(e))
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0')
下面是来自客户端的错误消息和标题
Content-Type: text/plain
Upgrade: websocket
Connection: Upgrade
Host: 10.1.1.61
Sec-Websocket-Key: 9eYtRDJj/SJ1MDMFsbT22w==
Sec-Websocket-Protocol:
Sec-Websocket-Version: 13
10.1.1.84 - - [19/May/2017 16:14:26] code 400, message Bad request syntax ('\x87\x00')
10.1.1.84 - - [19/May/2017 16:14:26] " " 400 -
我不知道是什么问题。我从客户端检查了标题 但是在任何地方都没有\ x87 \ x00。 最好是找出主要原因......但如果你推荐其他flask-websocket库或arduino库,我将不胜感激。 你能解决这个问题吗? 提前谢谢。
PS:我查了下面的文件,但没有用。 developer.mozilla.org/en/docs/WebSockets/Writing_WebSocket_servers