【得捷电子Follow me第4期】基础任务二:主控板建立TCPIP或UDP服务器
[复制链接]
这部分我们先看UDP协议,UDP他也是有例子的,我们可以查看下。
-
- #include <Ethernet.h>
-
- #include <EthernetUdp.h>
-
-
-
-
-
-
-
- byte mac[] = {
-
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-
- };
-
- IPAddress ip(192, 168, 2, 177);
-
-
-
- unsigned int localPort = 8888;
-
-
-
-
-
- char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
-
- char ReplyBuffer[] = "acknowledged";
-
-
-
-
-
- EthernetUDP Udp;
-
-
-
- void setup() {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Ethernet.init(17);
-
-
-
-
-
- Ethernet.begin(mac, ip);
-
-
-
-
-
- Serial.begin(9600);
-
- while (!Serial) {
-
- ;
-
- }
-
-
-
-
-
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
-
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
-
- while (true) {
-
- delay(1);
-
- }
-
- }
-
- if (Ethernet.linkStatus() == LinkOFF) {
-
- Serial.println("Ethernet cable is not connected.");
-
- }
-
-
-
-
-
- Udp.begin(localPort);
-
- }
-
-
-
- void loop() {
-
-
-
- int packetSize = Udp.parsePacket();
-
- if (packetSize) {
-
- Serial.print("Received packet of size ");
-
- Serial.println(packetSize);
-
- Serial.print("From ");
-
- IPAddress remote = Udp.remoteIP();
-
- for (int i=0; i < 4; i++) {
-
- Serial.print(remote[i], DEC);
-
- if (i < 3) {
-
- Serial.print(".");
-
- }
-
- }
-
- Serial.print(", port ");
-
- Serial.println(Udp.remotePort());
-
-
-
-
-
- Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
-
- Serial.println("Contents:");
-
- Serial.println(packetBuffer);
-
-
-
-
-
- Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
-
- Udp.write(ReplyBuffer);
-
- Udp.endPacket();
-
- }
-
- delay(10);
-
- }
这部分还比较好理解,主要就是创建一个UDP服务,端口是8888,通过电脑软件也建一个UDP服务连接他。
连接目标机器的IP地址和端口。
连接上之后会有反馈。接收信息也会打印的。
网络分析就是看数据段,数据是吻合的。
|