tcp和udp代码示例

简介: tcp和udp代码示例
#include <iostream>
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <unistd.h>
#include <sys/time.h>
#include <thread>

int tcp_client()
{
    // create socket
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    // connect server
    struct sockaddr_in addr;
    inet_pton(AF_INET, "192.168.0.203", &addr.sin_addr.s_addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8080);
    connect(sock_fd, (struct sockaddr *) &addr, sizeof(addr));
    // read and write
    char buf[1024] = {0};
    while (1)
    {
        int n = read(STDIN_FILENO, buf, sizeof(buf));
        write(sock_fd, buf, n);
        read(sock_fd, buf, sizeof (buf));
        std::cout << buf << std::endl;
    }
    // close
    close(sock_fd);
    return 0;
}

int tcp_server()
{
    // create socket
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    inet_pton(AF_INET, "192.168.0.159", &addr.sin_addr.s_addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8080);
    // bind
    int a = bind(sock_fd, (struct sockaddr *) &addr, sizeof(addr));
    // listen
    a = listen(sock_fd, 128);
    // accept
    struct sockaddr_in clientAddr;
    socklen_t len = sizeof(clientAddr);
    int cfd = accept(sock_fd, (struct sockaddr *) &clientAddr, &len);
    // read and write
    char buf[1024] = {0};
    while (1)
    {
        int n = read(STDIN_FILENO, buf, sizeof(buf));
        write(cfd, buf, n);
        read(cfd, buf, sizeof (buf));
        std::cout << buf << std::endl;
    }
    // close
    close(cfd);
    close(sock_fd);
}
// duojincheng cunczai henduo wenti
int fork_tcp_server()
{
    // create socket
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    inet_pton(AF_INET, "192.168.0.159", &addr.sin_addr.s_addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8081);
    // bind
    int a = bind(sock_fd, (struct sockaddr *) &addr, sizeof(addr));
    // listen
    a = listen(sock_fd, 128);
    // accept
    struct sockaddr_in clientAddr;
    socklen_t len = sizeof(clientAddr);
    while (1)
    {
        int cfd = accept(sock_fd, (struct sockaddr *) &clientAddr, &len);
        pid_t pid;
        pid = fork();
        if (pid < 0)
        {
            perror("fork error");
        }
        else if (pid == 0)
        {
            close(sock_fd);
            char buf[1024];
            int n = read(STDIN_FILENO, buf, sizeof(buf));
            if (n < 0)
            {
                perror("client error");
                close(cfd);
                break;
            }
            else if (n == 0)
            {
                printf("client close");
                close(cfd);
                break;
            }
            else
            {
                printf("%s\n", buf);
                write(cfd, buf, n);
            }
        }
        else
        {
            close(cfd);

        }
    }
    close(sock_fd);
}

int thread_tcp_server()
{
// create socket
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    inet_pton(AF_INET, "192.168.0.159", &addr.sin_addr.s_addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8081);
    // bind
    int a = bind(sock_fd, (struct sockaddr *) &addr, sizeof(addr));
    // listen
    a = listen(sock_fd, 128);
    // accept
    struct sockaddr_in clientAddr;
    socklen_t len = sizeof(clientAddr);
    while (1)
    {
        int cfd = accept(sock_fd, (struct sockaddr *) &clientAddr, &len);
        std::thread thread([&](){
            int c = cfd;
            char buf[1024] = {0};
            while (1)
            {
                int n = read(c, buf, sizeof (buf));
                write(c, buf, n);
                std::cout << buf << std::endl;
            }
        });
        thread.detach();
    }
    close(sock_fd);
}

int select_server()
{
    // create socket
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    inet_pton(AF_INET, "192.168.0.159", &addr.sin_addr.s_addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8081);
    // bind
    int a = bind(lfd, (struct sockaddr *) &addr, sizeof(addr));
    // listen
    a = listen(lfd, 128);
    // select
    int maxfd = lfd;
    fd_set oldSet, rSet;
    FD_ZERO(&oldSet);
    FD_ZERO(&rSet);
    FD_SET(lfd, &oldSet);
    while (1)
    {
        rSet = oldSet;
        int n = select(maxfd + 1, &rSet, 0, 0, 0);
        if (n < 0)
        {
            perror("error");
            break;
        }
        else if (n == 0)
        {
            continue;
        }
        else
        {
            // lfd
            if (FD_ISSET(lfd, &rSet))
            {
                struct sockaddr_in clientAddr;
                socklen_t len = sizeof(clientAddr);
                int cfd = accept(lfd, (struct sockaddr *) &clientAddr, &len);
                FD_SET(cfd, &oldSet);
                if (cfd > maxfd) maxfd = cfd;
                if (--n == 0)
                {
                    continue;
                }
            }
            // cfd
            for (int i = lfd + 1; i < maxfd + 1; i++)
            {
                if (FD_ISSET(i, &rSet))
                {
                    char buf[1500] = {0};
                    int ret = read(i, buf, sizeof(buf));
                    if (ret < 0)
                    {
                        perror("error");
                        close(i);
                        FD_CLR(i, &oldSet);
                    }
                    else if (ret==0)
                    {
                        perror("error");
                        close(i);
                        FD_CLR(i, &oldSet);
                    }
                    else
                    {
                        printf("%s \n", buf);
                    }
                }
            }
        }
    }
}

#define OPEN_MAX 1024
#define MAX_LINE 80

#include <sys/poll.h>
#include <cstring>

int poll_server()
{
    int i, j, maxi, lfd, connfd, sockfd;
    int nready;
    ssize_t n;
    char buf[MAX_LINE], str[INET_ADDRSTRLEN];
    socklen_t  clilen;
    struct pollfd client[OPEN_MAX];

    struct sockaddr_in cliaddr, servaddr;
    // create socket
    lfd = socket(AF_INET, SOCK_STREAM, 0);
    int opt = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    inet_pton(AF_INET, "192.168.0.159", &servaddr.sin_addr.s_addr);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(8081);
    // bind
    int a = bind(lfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
    // listen
    a = listen(lfd, 128);

//    client[0].
}
#include <sys/epoll.h>
int epoll_pipe()
{
    int fd[2];
    pipe(fd);

    pid_t pid;
    pid = fork();
    if (pid < 0)
    {
        perror("error");
    }
    else if (pid == 0)
    {
        close(fd[0]);
        char buf[5];
        char ch = 'a';
        while (1)
        {
            memset(buf, ch++, sizeof(buf));
            write(fd[1], buf, 5);
        }
    }
    else
    {
        close(fd[1]);
        int epfd = epoll_create(1);
        struct epoll_event ev, evs[1];
        ev.data.fd = fd[0];
        ev.events = EPOLLIN;
        epoll_ctl(epfd, EPOLL_CTL_ADD, fd[0], &ev);
        while (1)
        {
            int n = epoll_wait(epfd, evs, 1, -1);
            if (n == 1)
            {
                char buf[128] = {0};
                int ret = read(fd[0], buf, sizeof(buf));
                if (ret <= 0)
                {
                    close(fd[0]);
                    epoll_ctl(epfd, EPOLL_CTL_DEL, fd[0], &ev);
                    break;
                }
                else
                {
                    printf("%s\n", buf);
                }
            }
        }
    }
}

/**
  epoll.c
*/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/epoll.h>

#define PORT 8111
#define MSG_LEN 1024
#define MAX_EVENTS 20
#define TIMEOUT 500

int epoll_server()
{
    int ret = -1;
    int on = 1;
    int backlog = 10;
    int flags = 1;
    int socket_fd = -1;
    int epoll_fd = -1;;
    int event_num = 0;
    struct epoll_event ev, events[MAX_EVENTS];
    struct sockaddr_in    local_addr, remote_addr;
    char buff[MSG_LEN] = { 0 };

    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd < 0) {
        printf("create socket fd failed.\n");
        _exit(-1);
    }

    flags = fcntl(socket_fd, F_GETFL, 0);
    fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK);

    ret = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    if (ret < 0) {
        printf("set socket option failed.\n");
    }

    bzero(&local_addr, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(PORT);
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    ret = bind(socket_fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr));
    if (ret < 0) {
        printf("bind port[%d] failed.\n", PORT);
        _exit(-1);
    }

    ret = listen(socket_fd, backlog);
    if (ret < 0) {
        printf("listen socket[%d] port[%d] failed.\n", socket_fd, PORT);
        _exit(-1);
    }
    printf("listening on port[%d]...\n", PORT);

    epoll_fd = epoll_create(256);
    ev.events = EPOLLIN;
    ev.data.fd = socket_fd;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, socket_fd, &ev);

    while (1) {
        event_num = epoll_wait(epoll_fd, events, MAX_EVENTS, TIMEOUT);
        for (int i = 0; i < event_num; ++i)
        {
            if (events[i].data.fd == socket_fd) {
                socklen_t addr_len = sizeof(struct sockaddr);
                int accept_fd = accept(socket_fd, (struct sockaddr *)&remote_addr, &addr_len);
                flags = fcntl(accept_fd, F_GETFL, 0);
                fcntl(accept_fd, F_SETFL, flags | O_NONBLOCK);
                ev.events = EPOLLIN | EPOLLET;
                ev.data.fd = accept_fd;
                epoll_ctl(epoll_fd, EPOLL_CTL_ADD, accept_fd, &ev);
                printf("connection[%d] estasblished...\n", accept_fd);
            } else if (events[i].events & EPOLLIN) {
                memset(buff, 0, sizeof(buff));
                ret = recv(events[i].data.fd, (void *)buff, sizeof(buff), 0);

                if (ret <= 0) {
                    switch (errno) {
                        case EAGAIN:
                            printf("receive EAGAIN, break...\n");
                            break;
                        case EINTR:
                            do {
                                printf("index[%d] fd[%d] receive EINTR, rereceive...\n", i, events[i].data.fd);
                                memset(buff, 0, sizeof(buff));
                                ret = recv(events[i].data.fd, (void *)buff, sizeof(buff), 0);
                            } while (ret < 0 && errno == EINTR);
                            break;
                        default:
                            printf("receive ret[%d] fd[%d] errno[%d|%s]\n", ret, events[i].data.fd, errno, strerror(errno));
                            close(events[i].data.fd);
                            ev.events = EPOLLIN | EPOLLET;
                            ev.data.fd = events[i].data.fd;
                            epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, &ev);
                            break;
                    }
                }

                if (ret > 0) {
                    if (ret == MSG_LEN){
                        printf("maybe more data...\n");
                    }

                    buff[ret] = '\0';
                    printf("recv[%s]\n", buff);
                    send(events[i].data.fd, (void *)buff, strlen(buff), 0);
                }
            }
        }
    }
    close(socket_fd);
    return 0;
}

int udp_server()
{
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in myaddr;
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(9000);
    myaddr.sin_addr.s_addr = inet_addr("192.168.0.159");
    int ret = bind(fd, (struct sockaddr*)&myaddr, sizeof (myaddr));
    char buf[1500] = {0};
    struct sockaddr_in cliaddr;
    socklen_t len = sizeof (cliaddr);
    int n = 0;
    struct sockaddr_in dstaddr;
    dstaddr.sin_family = AF_INET;
    dstaddr.sin_port = htons(8888);
    dstaddr.sin_addr.s_addr = inet_addr("0.0.0.0");

    while (1)
    {
        n = recvfrom(fd, buf, sizeof (buf), 0, (struct sockaddr*)&cliaddr, &len);
        if (n < 0)
        {
            break;
        }
        else
        {
            printf("%s\n", buf);
            sendto(fd, buf, n, 0, (struct sockaddr*)&cliaddr, len);
        }
    }
    close(fd);
    return 0;
}

int main()
{
    udp_server();
    return 0;
}
目录
相关文章
|
4天前
|
存储 网络协议 安全
用于 syslog 收集的协议:TCP、UDP、RELP
系统日志是从Linux/Unix设备及网络设备生成的日志,可通过syslog服务器集中管理。日志传输支持UDP、TCP和RELP协议。UDP无连接且不可靠,不推荐使用;TCP可靠,常用于rsyslog和syslog-ng;RELP提供可靠传输和反向确认。集中管理日志有助于故障排除和安全审计,EventLog Analyzer等工具可自动收集、解析和分析日志。
|
20天前
|
网络协议 网络性能优化 数据处理
深入解析:TCP与UDP的核心技术差异
在网络通信的世界里,TCP(传输控制协议)和UDP(用户数据报协议)是两种核心的传输层协议,它们在确保数据传输的可靠性、效率和实时性方面扮演着不同的角色。本文将深入探讨这两种协议的技术差异,并探讨它们在不同应用场景下的适用性。
54 4
|
20天前
|
监控 网络协议 网络性能优化
网络通信的核心选择:TCP与UDP协议深度解析
在网络通信领域,TCP(传输控制协议)和UDP(用户数据报协议)是两种基础且截然不同的传输层协议。它们各自的特点和适用场景对于网络工程师和开发者来说至关重要。本文将深入探讨TCP和UDP的核心区别,并分析它们在实际应用中的选择依据。
47 3
|
1月前
|
网络协议 算法 网络性能优化
|
1月前
|
网络协议 SEO
TCP连接管理与UDP协议IP协议与ethernet协议
TCP、UDP、IP和Ethernet协议是网络通信的基石,各自负责不同的功能和层次。TCP通过三次握手和四次挥手实现可靠的连接管理,适用于需要数据完整性的场景;UDP提供不可靠的传输服务,适用于低延迟要求的实时通信;IP协议负责数据包的寻址和路由,是网络层的重要协议;Ethernet协议定义了局域网的数据帧传输方式,广泛应用于局域网设备之间的通信。理解这些协议的工作原理和应用场景,有助于设计和维护高效可靠的网络系统。
39 4
|
1月前
|
缓存 负载均衡 网络协议
面试:TCP、UDP如何解决丢包问题
TCP、UDP如何解决丢包问题。TCP:基于数据块传输/数据分片、对失序数据包重新排序以及去重、流量控制(滑动窗口)、拥塞控制、自主重传ARQ;UDP:程序执行后马上开始监听、控制报文大小、每个分割块的长度小于MTU
|
2月前
|
网络协议 前端开发 物联网
TCP和UDP区别?
本文首发于微信公众号“前端徐徐”,详细介绍了TCP和UDP两种传输层协议的核心概念、连接性和握手过程、数据传输和可靠性、延迟和效率、应用场景及头部开销。TCP面向连接、可靠、有序,适用于网页浏览、文件传输等;UDP无连接、低延迟、高效,适用于实时音视频传输、在线游戏等。
65 1
TCP和UDP区别?
|
2月前
|
Web App开发 缓存 网络协议
不为人知的网络编程(十八):UDP比TCP高效?还真不一定!
熟悉网络编程的(尤其搞实时音视频聊天技术的)同学们都有个约定俗成的主观论调,一提起UDP和TCP,马上想到的是UDP没有TCP可靠,但UDP肯定比TCP高效。说到UDP比TCP高效,理由是什么呢?事实真是这样吗?跟着本文咱们一探究竟!
63 10
|
2月前
|
网络协议 网络性能优化 C#
C# 一分钟浅谈:UDP 与 TCP 协议区别
【10月更文挑战第8天】在网络编程中,传输层协议的选择对应用程序的性能和可靠性至关重要。本文介绍了 TCP 和 UDP 两种常用协议的基础概念、区别及应用场景,并通过 C# 代码示例详细说明了如何处理常见的问题和易错点。TCP 适用于需要可靠传输和顺序保证的场景,而 UDP 适用于对延迟敏感且可以容忍一定数据丢失的实时应用。
50 1
|
2月前
|
网络协议 Linux 网络性能优化
Linux C/C++之TCP / UDP通信
这篇文章详细介绍了Linux下C/C++语言实现TCP和UDP通信的方法,包括网络基础、通信模型、编程示例以及TCP和UDP的优缺点比较。
45 0
Linux C/C++之TCP / UDP通信