我正在尝试将PC上的消息发送到板上,但是问题是我在决定发送消息之前一直保持连接中断。
这是我从中发送消息的代码。我创建了一个插座,连接到板上,然后等待来自Scanner对象的输入。得到一些输入后,我会向董事会发送一条消息。
客户
Socket socket = new Socket();
socket.connect(new InetSocketAddress("192.168.4.1",3000));
Scanner in = new Scanner(System.in);
String message = DataProtocol.sendMessageFormat("KLASA","METHOD","FILIP CACIC");
String message1 = DataProtocol.sendMessageFormat("KLASA","METHOD","FILIP CACIC");
message = message1 + message;
OutputStream outputStream = socket.getOutputStream();
String line;
while(!(line = in.nextLine()).equals("EXIT")){
outputStream.write(message.getBytes());
outputStream.flush();
}
这是recv.message
的代码。
服务器
void CommunicationProcessor::readFromStream(WiFiClient* wifiClient){
CLIENT_ACTIVE = true;
while(CLIENT_ACTIVE){
Serial.println(wifiClient->connected()); -> returns 1
int bytesRead = wifiClient->readBytes(buffer,1024); -> returns 0
Serial.println(wifiClient->connected()); -> returns 0
dataManager.appendData(bufferReader.getDataReaded(buffer,bytesRead));
if (checkIfEndLine(bytesRead)){
handleDataRecv();
dataManager.clearBuffer();
}
}
Serial.println("CLIENT QUIT");
}
在方法readBytes
之前,我调用了方法connected()
,它返回了1
。所以一切都很好。
方法readBytes返回0
,因为我尚未发送任何消息。
之后,我再打一次connected()
,这次返回0
。
现在,如果我删除此Scanner对象并从代码中循环并立即发送消息,则服务器将恢复。消息。
Socket socket = new Socket();
socket.connect(new InetSocketAddress("192.168.4.1",3000));
Scanner in = new Scanner(System.in);
String message = DataProtocol.sendMessageFormat("KLASA","METHOD","FILIP CACIC");
String message1 = DataProtocol.sendMessageFormat("KLASA","METHOD","FILIP CACIC");
message = message1 + message;
OutputStream outputStream = socket.getOutputStream();
outputStream.write(message.getBytes());
outputStream.close();
我的问题是为什么在调用方法readBytes
之后关闭连接?
编辑
我刚刚使用此代码进行了测试,但连接仍然丢失。 “ Client alive”行仅打印一次。
服务器
void loop(){
delay(1000);
if (client){
Serial.println("Client alive");
Serial.println(client.connected());
}else{
client = server.available();
if (client){
Serial.println(client.connected());
}
} }
编辑2
我发现了问题。我将板卡用作WIFI-ACCESS POINT,但是将板卡连接到路由器和PC时,一切正常。 所以现在我的问题是为什么当板配置为ACCESS-POINT时我会失去连接?
编辑3
我找到了引起问题的原因。我在连接到wifi接入点时遇到问题,所以我调用了方法WIFI.persistent(false),这导致Java中的管道中断(流关闭)。