說明
傳統的server.available()函數隻會在發送數據後告訴你一個新的客戶端,這使得FTP等一些協議無法正確實現。
目的是程序將使用available() 或accept(),但不能同時使用兩者。使用available(),客戶端連接繼續由 EthernetServer 管理。您不需要保留客戶端對象,因為調用 available() 將為您提供客戶端發送的任何數據。使用available() 可以用很少的代碼編寫簡單的服務器。
使用accept(),EthernetServer 隻為您提供一次客戶端,無論它是否已發送任何數據。您必須跟蹤連接的客戶端。這需要更多代碼,但您可以獲得更多控製權。
用法
server.accept()
參數
空
返回
- 一個客戶對象。如果沒有客戶端可以讀取數據,則此對象將在 if-statement 中評估為 false。 (以太網客戶端)。
示例
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 69, 104);
// telnet defaults to port 23
EthernetServer server(23);
EthernetClient clients[8];
void setup() {
Ethernet.begin(mac, ip);
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start listening for clients
server.begin();
}
void loop() {
// check for any new client connecting, and say hello (before any incoming data)
EthernetClient newClient = server.accept();
if (newClient) {
for (byte i = 0; i < 8; i++) {
if (!clients[i]) {
newClient.print("Hello, client number: ");
newClient.println(i);
// Once we "accept", the client is no longer tracked by EthernetServer
// so we must store it into our list of clients
clients[i] = newClient;
break;
}
}
}
// check for incoming data from all clients
for (byte i = 0; i < 8; i++) {
while (clients[i] && clients[i].available() > 0) {
// read incoming data from the client
Serial.write(clients[i].read());
}
}
// stop any clients which disconnect
for (byte i = 0; i < 8; i++) {
if (clients[i] && !clients[i].connected()) {
clients[i].stop();
}
}
}
相關用法
- Arduino Ethernet - server.available()用法及代碼示例
- Arduino Ethernet - server.begin()用法及代碼示例
- Arduino Ethernet - server.write()用法及代碼示例
- Arduino Ethernet - EthernetUDP.parsePacket()用法及代碼示例
- Arduino Ethernet - Ethernet.setRetransmissionTimeout()用法及代碼示例
- Arduino Ethernet - Ethernet.MACAddress()用法及代碼示例
- Arduino Ethernet - Ethernet.hardwareStatus()用法及代碼示例
- Arduino Ethernet - client.setConnectionTimeout()用法及代碼示例
- Arduino Ethernet - client.connected()用法及代碼示例
- Arduino Ethernet - EthernetUDP.beginPacket()用法及代碼示例
- Arduino Ethernet - EthernetUDP.available()用法及代碼示例
- Arduino Ethernet - Ethernet.localIP()用法及代碼示例
- Arduino Ethernet - EthernetUDP.read()用法及代碼示例
- Arduino Ethernet - EthernetUDP.endPacket()用法及代碼示例
- Arduino Ethernet - Ethernet.setDnsServerIP()用法及代碼示例
- Arduino Ethernet - client.remotePort()用法及代碼示例
- Arduino Ethernet - EthernetUDP.begin()用法及代碼示例
- Arduino Ethernet - Ethernet.init()用法及代碼示例
- Arduino Ethernet - Ethernet.setMACAddress()用法及代碼示例
- Arduino Ethernet - if(server)用法及代碼示例
- Arduino Ethernet - client.available()用法及代碼示例
- Arduino Ethernet - UDP.remotePort()用法及代碼示例
- Arduino Ethernet - EthernetServer()用法及代碼示例
- Arduino Ethernet - Ethernet.setSubnetMask()用法及代碼示例
- Arduino Ethernet - UDP.remoteIP()用法及代碼示例
注:本文由純淨天空篩選整理自arduino.cc大神的英文原創作品 Ethernet - server.accept()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。