【Linux后端服务器开发】UDP协议

目录

一、端口号

二、UDP报头格式

三、UDP的特点

四、UDP协议实现网络聊天群


一、端口号

端口号port标识了一个主机上进行通信的不同的应用程序。

  • 0 ~ 1023:系统端口号,HTTP、FTP、SSH等这些广为使用的应用层协议,它们的端口号都是固定的系统端口号(知名端口号)
  • 1024 ~ 65535:操作系统动态分配的端口号,客户端程序的端口号,可有操作系统分配或程序员分配(普通端口号)

知名端口号(Well-Know Port Number):

  • ftp服务器:21
  • ssh服务器:22
  • telnet服务器:23
  • http服务器:80
  • https服务器:443

查看知名端口号:cat /etc/services

netstat:一个用来查看网络状态的重要工具

语法:netstat -[选项]

  • n:拒绝显示别名,能显示数字的全部显示数字
  • l:仅列出有在 listen 状态的服务状态
  • p:显示建立相关连接的程序名
  • t:仅显示tcp相关选项
  • u:仅显示udp相关选项
  • a:显示所有选项,默认不显示 listen 相关

pidof:查看服务器的进程id(通过进程名查看进程id)

语法:pidof [进程名]

端口号 -----> 进程(唯一关系)

  • 一个端口号是否可以被多个进程bind?不可以,端口号指向进程必须唯一
  • 一个进程是否可以绑定多个端口号?可以,进程指向端口号不一定唯一

二、UDP报头格式

  • 16位UDP长度,表示整个数据报(UDP首部+UDP数据)的最大长度(64K)
  • 如果检验和出错,数据直接丢弃
  • 定长报头,报头的本质是结构化数据

三、UDP的特点

UDP传输的过程类似于寄信:

  • 无连接:知道对端的IP和端口号就直接进行传输,不需要建立连接
  • 不可靠:没有确认机制,没有重传机制,如果因为网络故障导致数据段无法发送,UDP协议层也不会给应用层返回任何错误信息
  • 面向数据报:应用层交给UDP多长的报文,UDP原样发送,既不会拆分,也不会合并,不能够灵活的控制读写数据的次数和数量

UDP的缓冲区:

  • UDP没有真正意义上的发送缓冲区,调用sendto会直接交给内核,由内核将数据报传给网络层协议进行后续的传输处理
  • UDP具有接收缓冲区,但是这个接收缓冲区不能保证收到的UDP报文的顺序和发送UDP报文的顺序一致;如果缓冲区满了,再到达的UDP数据就会被丢弃

UDP的socket既能读,也能写,这就是全双工概念。

基于UDP的常用应用层协议:

  • NFS:网络文件系统
  • TFTP:简单的文件传输协议
  • DHCP:动态主机配置协议
  • BOOTP:启动协议(用于无盘设备启动)
  • DNS:域名解析协议

UDP协议的应用场景多为视频网站、直播平台等不担心数据包丢失的情况。

四、UDP协议实现网络聊天群

设计思路:

  • 服务器与客户端通过udp协议通信,即server和client都需要创建自己的socket套接字
  • server创建完socket套接字之后,需要将server自身的ip和port和套接字bind绑定client的套接字不需要显式bind绑定(由OS自动绑定)
  • server先运行 ,通过**recvfrom()**向数据的接收缓冲区循环读取数据
  • client在运行的时候指定server的ip和port ,通过**sendto()**向服务器的接收缓冲区发送数据
  • User.h头文件,进行在线用户管理 ,通过ip和port形成用户信息结构体,可以进行在线用户的添加、删除、判断,并且在server接收到数据的时候,进行广播(对所有在线用户发送刚刚接收到的数据)
  • 所有在线用户信息通过一个静态全局变量的哈希表管理,key值是ip-port组成的字符串
  • client在运行的时候就会进行一次线程分离,分离出去的线程循环读取并打印client自身的接收缓冲区内的数据(来自广播的数据)

**设计效果:**当多个client连接server之后,只要是online登录了的用户,都可以向server发送数据的同时看到自己和其他登录用户发送的数据,这就是网络聊天群

User.h

cpp 复制代码
#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unordered_map>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

class User
{
public:
    User(const std::string& ip, const uint16_t& port)
        : _ip(ip), _port(port)
    {}

    std::string ip()
    {
        return _ip;
    }

    uint16_t port()
    {
        return _port;
    }

private:
    std::string _ip;
    uint16_t _port;
};

class OnlineUser
{
public:
    OnlineUser()
    {}

    void AddUser(const std::string& ip, const uint16_t& port)
    {
        std::string id = ip + "-" + std::to_string(port);
        _users.insert(std::make_pair(id, User(ip, port)));
    }

    void DelUser(const std::string& ip, const uint16_t& port)
    {
        std::string id = ip + "-" + std::to_string(port);
        _users.erase(id);
    }

    bool IsOnline(const std::string& ip, const uint16_t& port)
    {
        std::string id = ip + "-" + std::to_string(port);
        return _users.find(id) != _users.end();
    }

    void BroadcastMessage(int sockfd, const std::string& message, const std::string& ip, const uint16_t& port)
    {
        for (auto& user : _users)
        {
            struct sockaddr_in client;
            client.sin_family = AF_INET;
            client.sin_addr.s_addr = inet_addr(user.second.ip().c_str());
            client.sin_port = htons(user.second.port());

            std::string s = "[" + ip + "-" + std::to_string(port) + "]" + "# " + message;
            sendto(sockfd, s.c_str(), s.size(), 0, (struct sockaddr*)&client, sizeof(client));
        }
    }

private:
    std::unordered_map<std::string, User> _users;
};

server.cpp

cpp 复制代码
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <functional>
#include <memory>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "User.h"

using namespace std;

typedef function<void(int, string, uint16_t, string)> func_t;
static string defaultIP = "0.0.0.0";

class UdpServer
{
public:
    UdpServer(const func_t& func, const uint16_t& port, const string& ip = defaultIP)
        : _cb(func), _port(port), _ip(ip)
    {}

    void Init()
    {
        // 1. 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            cerr << "socket error: " << errno << strerror(errno) << endl;
            exit(errno);
        }

        // 2. 绑定 ip:port
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = htonl(INADDR_ANY);    // Address to accept any incomit message -------> 任意地址绑定
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());     // string ---> uint32_t ---> htonl
        local.sin_port = htons(_port);
        
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if (n < 0)
        {
            cerr << "bind error: " << errno << strerror(errno) << endl;
            exit(errno);
        }
    }

    void Start()
    {
        char buf[1024];
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t peer_len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&peer, &peer_len);
            if (n > 0)
            {
                buf[n] = 0;
                string client_ip = inet_ntoa(peer.sin_addr);     // 网络序列 ---> 整型 ---> 点分十进制
                uint16_t client_port = ntohs(peer.sin_port);   
                string message = buf;
                cout << client_ip << "[" << client_port << "]# " << message << endl;

                _cb(_sockfd, client_ip, client_port, message);
            }
        }
    }

private:
    string _ip;
    uint16_t _port;
    int _sockfd;
    func_t _cb;
};

// 聊天群在线用户,静态全局变量
static OnlineUser g_online_users;

// 处理message,server与业务逻辑解耦
void RouteMessage(int sockfd, string client_ip, uint16_t client_port, string message)
{
    if (message == "online")
        g_online_users.AddUser(client_ip, client_port);
    if (message == "offline")
        g_online_users.DelUser(client_ip, client_port);

    if (g_online_users.IsOnline(client_ip, client_port))
    {
        g_online_users.BroadcastMessage(sockfd, message, client_ip, client_port);
    }
    else
    {
        struct sockaddr_in client;
        bzero(&client, sizeof(client));
        client.sin_family = AF_INET;
        client.sin_addr.s_addr = inet_addr(client_ip.c_str());
        client.sin_port = htons(client_port);

        string response = "你还没有登录,请输入online登录加入聊天群";
        sendto(sockfd, response.c_str(), response.size(), 0, (struct sockaddr*)&client, sizeof(client));
    }
}

void Usage()
{
    cout << "Usage: \n\t" << "server port" << endl;
    exit(1);
}

int main(int args, char* argv[])
{
    if (args != 2)
        Usage();

    uint16_t port = atoi(argv[1]);

    unique_ptr<UdpServer> udp_server(new UdpServer(RouteMessage, port));

    udp_server->Init();
    udp_server->Start();
    
    return 0;
}

client.cpp

cpp 复制代码
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <functional>
#include <pthread.h>
#include <memory>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "User.h"

using namespace std;

class UdpClient
{
public:
    UdpClient(const string& server_ip, const uint16_t& server_port)
        : _server_ip(server_ip), _server_port(server_port), _sockfd(-1), _quit(false)
    {}

    void Init()
    {
        // 1. 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        assert(_sockfd != -1);
        cout << "socket seccess: " << _sockfd << endl;

        // 2. 绑定bind,不需要显示绑定,由os分配
    }

    static void* ReadMessage(void* args)
    {
        int sockfd = *(static_cast<int*>(args));
        pthread_detach(pthread_self());     // 线程分离

        while (true)
        {
            char buf[1024];
            struct sockaddr_in tmp;
            socklen_t tmp_len = sizeof(tmp);
            ssize_t n = recvfrom(sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&tmp, &tmp_len);
            if (n >= 0)
                buf[n] = 0;
            cout << "\r" << buf << "\n";
        }

        return nullptr;
    }

    void Run()
    {
        pthread_create(&_reader, nullptr, ReadMessage, (void*)&_sockfd);

        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(_server_ip.c_str());
        server.sin_port = htons(_server_port);

        string message;
        while (!_quit)
        {
            fprintf(stderr, "Enter:# ");
            fflush(stderr);
            getline(cin, message);
            message[message.size()] = 0;
            
            sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));
            usleep(100);
        }
    }

private:
    string _server_ip;
    uint16_t _server_port;
    int _sockfd;
    bool _quit;

    pthread_t _reader;
};

void Usage()
{
    cout << "Usage: \n\t" << "client ip port" << endl;
}

int main(int args, char* argv[])
{
    if (args != 3)
        Usage();

    string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    unique_ptr<UdpClient> udp_client(new UdpClient(server_ip, server_port));

    udp_client->Init();
    udp_client->Run();

    return 0;
}

运行效果:

相关推荐
Hugo_McQueen5 分钟前
pWnos1.0 靶机渗透 (Perl CGI 的反弹 shell 利用)
linux·服务器·网络安全
XY.散人24 分钟前
初识Linux · 文件(1)
linux·运维·服务器
叶北辰CHINA2 小时前
nginx反向代理,负载均衡,HTTP配置简述(说人话)
linux·运维·nginx·http·云原生·https·负载均衡
不惑_2 小时前
在 Ubuntu 安装 Python3.7(没有弯路)
linux·运维·ubuntu
玉树临风江流儿3 小时前
Linux驱动开发(速记版)--设备模型
linux·驱动开发
杰哥在此3 小时前
Python知识点:如何使用Multiprocessing进行并行任务管理
linux·开发语言·python·面试·编程
枫叶丹46 小时前
【在Linux世界中追寻伟大的One Piece】进程信号
linux·运维·服务器
刻词梨木6 小时前
ubuntu中挂载点内存不足,分配不合理后使用软链接的注意事项
linux·运维·ubuntu
灯火不休ᝰ7 小时前
[win7] win7系统的下载及在虚拟机中详细安装过程(附有下载文件)
linux·运维·服务器
数云界9 小时前
如何在 DAX 中计算多个周期的移动平均线
java·服务器·前端