我正在使用带有socket.io的React Native来使用套接字将数据发送到Arduino。我只是感到困惑,因为我的arduino将这个字符串打印为输出(而不是"hello world")
GET /socket.io/?EIO=3&transport=polling&t=N3MDU9z HTTP/1.1
accept: */*
Host: 192.168.1.109
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/3.12.1我在我的ESP8266上运行了以下代码来接收和打印来自客户端的字符串
#include "ESP8266WiFi.h"
const char* ssid = "SSID";
const char* password = "PASSWORD";
WiFiServer wifiServer(80);
void setup() {
Serial.begin(115200);
delay(1000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting..");
}
Serial.print("Connected to WiFi. IP:");
Serial.println(WiFi.localIP());
wifiServer.begin();
}
void loop() {
WiFiClient client = wifiServer.available();
if (client) {
while (client.connected()) {
while (client.available()>0) {
char c = client.read();
Serial.write(c);
}
delay(10);
}
client.stop();
Serial.println("Client disconnected");
}
}下面是客户端的代码(js)
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import io from 'socket.io-client';
export default class App extends React.Component{
constructor(props) {
super(props);
}
componentDidMount() {
const socket = io("http://192.168.1.109:80");
socket.emit("message","hello world");
}
render(){
return(
<View style={styles.container}>
<Text>Hello</Text>
</View>
)
}
}有人有什么建议吗?
发布于 2020-03-14 08:03:02
您的React代码正在使用HTTP协议打开到ESP8266的连接。
ESP8266 WiFiClient类是一个原始的TCP客户端,而不是一个HTTP服务器。因此,当您打印它接收到的内容时,您打印的是您的React代码发送的HTTP协议行。这就是为什么你会看到你所看到的。
换句话说,socket.io使用的是建立在超文本传输协议之上的协议。您的代码只使用TCP,所以它只看到HTTP。它不会响应HTTP消息,并且永远不会看到您尝试发送的数据,因为您没有使用该协议。
如果你真的想使用socket.io (为什么?)然后,您需要为ESP8266找到一个socket.io库并使用它。否则,您将需要自己实现socket.io协议。有一个here,但我不确定它是否能满足您的需求。
不幸的是,socket.io是一个命名的软件。在计算的其他领域,“套接字”更多地是指原始TCP连接;他们选择令人困惑地重复使用这个名称来表示构建在TCP之上的几层的协议。Linux下的TCP "socket“和socket.io的"socket”是不一样的。Linux下的TCP“WiFiClient”和ESP8266套接字是一样的(它的名字也很不幸,因为它不是特定于WiFi的)。
https://stackoverflow.com/questions/60678384
复制相似问题