【嵌入式学习】网络通信基础-Day2-TCP和UDP基础通信模型

思维导图&笔记

见原文:EmbeddedNote:TCP和UDP基础通信模型 - Jun (lingjun.life)

UDP机械臂测试

机械臂
通过w(红色臂角度增大)s(红色臂角度减小)d(蓝色臂角度增大)a(蓝色臂角度减小)按键控制机械臂
注意:关闭计算机的杀毒软件,电脑管家,防火墙
1)基于UDP服务器的机械臂,端口号是8888, ip是Windows的ip;
查看Windows的IP:按住Windows+r 按键,输入cmd , 输入ipconfig
2)点击软件中的开启监听;
3)机械臂需要发送16进制数,共5个字节,协议如下

    0xff    0x02    x   y   0xff
0xff:起始结束协议,固定的;
0x02:控制机械手臂协议,固定的;
x:指定要操作的机械臂
    0x00 红色摆臂
    0x01 蓝色摆臂
y:指定角度

【嵌入式学习】网络通信基础-Day2-TCP和UDP基础通信模型_第1张图片

/*
 * Filename: 02tcpClint.c
 * Author: linus
 * Date: 2024-01-12
 * Version: 1.0
 *
 * Description: The purpose of this code.
 */

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 
#include 
#include 

int cfd;
struct sockaddr_in cin;
char send_buf[5];

int RobArmCtl(char buf[128])
{
    static int x = 0, y = 0;

    switch (buf[0])
    {
    case 'W':
        x++;
        send_buf[2] = 0x00;
        send_buf[3] = x;
        break;
    case 'S':
        send_buf[2] = 0x00;
        send_buf[3] = x;
        x--;
        break;
    case 'A':
        y++;
        send_buf[2] = 0x01;
        send_buf[3] = y;
        break;
    case 'D':
        y--;
        send_buf[2] = 0x01;
        send_buf[3] = y;
        break;
    default:
        break;
    }

    send_buf[0] = 0xff;
    send_buf[1] = 0x02;

    send_buf[4] = 0xff;
    write(cfd, send_buf, sizeof(send_buf));
}

int init()
{
    send_buf[0] = 0xff;
    send_buf[1] = 0x02;
    send_buf[2] = 0x00;
    send_buf[3] = 0x00;
    send_buf[4] = 0xff;
    write(cfd, send_buf, sizeof(send_buf));

    send_buf[0] = 0xff;
    send_buf[1] = 0x02;
    send_buf[2] = 0x01;
    send_buf[3] = 90;
    send_buf[4] = 0xff;
    write(cfd, send_buf, sizeof(send_buf));
}

int main(int argc, const char *argv[])
{
    // 创建套接字
    cfd = socket(AF_INET, SOCK_STREAM, 0);

    cin.sin_family = AF_INET;
    cin.sin_port = htons(8888);
    cin.sin_addr.s_addr = inet_addr("192.168.125.27");

    // 连接服务器
    connect(cfd, (struct sockaddr *)&cin, sizeof(cin));
    init();

    char buf[128] = "";
    while (1)
    {
        printf("请输入指令:");
        fgets(buf, sizeof(buf), stdin);
        buf[strlen(buf) - 1] = '\0';
        RobArmCtl(buf);
        printf("指令发送成功\n");
    }

    return 0;
}

【嵌入式学习】网络通信基础-Day2-TCP和UDP基础通信模型_第2张图片

你可能感兴趣的:(学习,tcp/ip,udp)