Linux下的简单TCP客户端和服务器

客户端

cpp 复制代码
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>

int main()
{
    struct sockaddr_in* caddr=(struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
    caddr->sin_port = htons(8999);
    inet_pton(AF_INET, "192.168.101.231", &caddr->sin_addr.s_addr);
    caddr->sin_family = AF_INET;

    int cfd = socket(AF_INET, SOCK_STREAM, 0);
    if (cfd == -1)
    {
        perror("socket error");
        return 1;
    }

    int res = connect(cfd, (struct sockaddr*)caddr, sizeof(struct sockaddr));
    if (res == -1)
    {
        perror("connect error");
        return 1;
    }

    while (1)
    {
        char buf[1024] = {'\0'};
        int res = send(cfd, "this is client", strlen("this is client"), 0);
        if (res != -1)
        {
            printf("send:%s\n", "this is client");
        }
        else
        {
            perror("send error");
        }
        res = recv(cfd, buf, 1024, 0);
        if (res == -1)
        {
            perror("recv error");
        }
        else
        {
            printf("client recv:%s\n", buf);
        }
        memset(buf, 0, 1024);
    }

    close(cfd);
    return 0;
}

服务器

cpp 复制代码
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>

int main()
{
    struct sockaddr_in saddr;
    saddr.sin_port = htons(8999);
    saddr.sin_addr.s_addr = INADDR_ANY;
    saddr.sin_family = AF_INET;
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sfd == -1)
    {
        perror("socket error");
        return 1;
    }
    int bind_res = bind(sfd, (struct sockaddr*)&saddr, sizeof(struct sockaddr_in));
    if (bind_res == -1)
    {
        perror("bind error");
        return 1;
    }
    listen(sfd, 100);
    int size = sizeof(struct sockaddr_in);
    int cfd = accept(sfd, (struct sockaddr*)&saddr, (socklen_t*)&size);
    while (1)
    {


        if (cfd == -1)
        {
            perror("accept error");
            return 1;
        }

        char buf[1024] = {'\0'};
        int res = recv(cfd, buf, 1024, 0);
        if (res != -1)
        {
            printf("recv:%s\n", buf);
        }
        strcat(buf, ": is recved by server");
        res = send(cfd, buf, strlen(buf), 0);
        if (res == -1)
        {
            perror("send error");
        }
        memset(buf, 0, 1024);

    }
    close(cfd);
    close(sfd);
    return 0;
}

运行结果:

客户端:

服务器

相关推荐
AA陈超1 小时前
ASC学习笔记0020:用于定义角色或Actor的默认属性值
c++·笔记·学习·ue5·虚幻引擎
coderxiaohan1 小时前
【C++】仿函数 + 模板进阶
开发语言·c++
dreamtm1231 小时前
通俗理解 TCP 拥塞控制:像 “快递员看路况调速”,避免网络 “堵车”
网络·tcp/ip·php
Cult Of1 小时前
TCP 与 UDP 的区别
网络协议·tcp/ip·udp
wanhengidc2 小时前
云手机的软件核心是什么
运维·服务器·web安全·游戏·智能手机
IMPYLH2 小时前
Lua 的 collectgarbage 函数
开发语言·笔记·junit·单元测试·lua
百锦再2 小时前
第18章 高级特征
android·java·开发语言·后端·python·rust·django
Tony Bai3 小时前
Go 在 Web3 的统治力:2025 年架构与生态综述
开发语言·后端·架构·golang·web3
芬加达3 小时前
jvm八股
运维·服务器·jvm