首页 > 系统相关 >Linux下TCP/IP编程--TCP实战

Linux下TCP/IP编程--TCP实战

时间:2024-03-29 10:37:49浏览次数:29  
标签:received socket -- IP TCP server client address include

之前尝试过windows下的简单TCP客户端服务器编写,这次尝试下一下Linux环境下的TCP

客户端代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

struct CustomMessage {
    char university[4]; // "AHU\0"
    char major[32]; // 专业
    char data[256]; // 消息数据
};

int main() {
    int client_socket;
    struct sockaddr_in server_address;

    // 创建套接字
    client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址
    memset(&server_address, 0, sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(8888);
    if (inet_pton(AF_INET, "127.0.0.1", &server_address.sin_addr) <= 0) {
        perror("Invalid IP address");
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    // 连接服务器
    if (connect(client_socket, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) {
        perror("Connection failed");
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    while (1) {
        // 获取用户输入的消息
        printf("请输入要发送的消息 (输入 exit 结束): ");
        struct CustomMessage message_to_send;
        fgets(message_to_send.data, sizeof(message_to_send.data), stdin);
        message_to_send.data[strcspn(message_to_send.data, "\n")] = '\0'; // 移除换行符
        strcpy(message_to_send.university, "AHU"); // 设置学校为"AHU"
        strcpy(message_to_send.major, "CS"); // 设置专业为"CS"

        // 发送自定义消息
        int bytes_sent = send(client_socket, (const char*)&message_to_send, sizeof(struct CustomMessage), 0);
        if (bytes_sent < 0) {
            perror("Send failed");
            close(client_socket);
            exit(EXIT_FAILURE);
        }

        // 如果用户输入 "exit",结束循环
        if (strcmp(message_to_send.data, "exit") == 0) {
            break;
        }
    }

    // 关闭客户端套接字
    close(client_socket);

    return 0;
}

服务器端代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 8888
#define MAX_PENDING_CONNECTIONS 5

struct CustomMessage {
    char university[4];
    char major[32];
    char data[256];
};

int main() {
    int server_socket, client_socket;
    struct sockaddr_in server_address, client_address;
    socklen_t client_address_length = sizeof(client_address);

    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    memset(&server_address, 0, sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = INADDR_ANY;
    server_address.sin_port = htons(PORT);

    if (bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) {
        perror("Bind failed");
        close(server_socket);
        exit(EXIT_FAILURE);
    }

    if (listen(server_socket, MAX_PENDING_CONNECTIONS) < 0) {
        perror("Listen failed");
        close(server_socket);
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port %d...\n", PORT);

    while (1) {
        client_socket = accept(server_socket, (struct sockaddr*)&client_address, &client_address_length);
        if (client_socket < 0) {
            perror("Accept failed");
            close(server_socket);
            exit(EXIT_FAILURE);
        }

        while (1) {
            struct CustomMessage received_message;
            ssize_t bytes_received = recv(client_socket, (char*)&received_message, sizeof(struct CustomMessage), 0);
            if (bytes_received > 0) {
                printf("Received Message:\n");
                printf("University: %s\n", received_message.university);
                printf("Major: %s\n", received_message.major);
                printf("Data: %s\n", received_message.data);

                if (strcmp(received_message.data, "exit") == 0) {
                    close(client_socket);
                    break;
                }
            }
            else if (bytes_received == 0) {
                printf("Client disconnected\n");
                close(client_socket);
                break;
            }
            else {
                perror("Receive failed");
                close(client_socket);
                break;
            }
        }
    }

    close(server_socket);

    return 0;
}

运行结果

image

标签:received,socket,--,IP,TCP,server,client,address,include
From: https://www.cnblogs.com/haof31/p/18103229

相关文章

  • 短视频文案提取的简单实现
    ​ 过春风十里,尽荠麦青青。春天总是让人舒坦,而今年的三月,也因为与媳妇结婚十年,显得格外不同。两人奢侈的请了一天假,瞒着孩子,重游西湖,去寻找13年前的冰棍店(给当时还是同事的她买了最贵的一个雪糕-8元),去寻找13年前卖红豆钥匙扣的大爷(她送我了一个绿豆的钥匙扣-纯洁的友谊),去坐一坐1......
  • Java实现的表达式求值算法(包括加减乘除以及括号运算)
    packagecom.example.demo.java;importcom.greenpineyu.fel.FelEngine;importcom.greenpineyu.fel.FelEngineImpl;importjava.math.BigDecimal;importjava.util.HashMap;importjava.util.Map;importjava.util.Stack;importjava.util.regex.Matcher;impor......
  • [apue] 进程控制那些事儿
    进程标识在介绍进程的创建、启动与终止之前,首先了解一下进程的唯一标识——进程ID,它是一个非负整数,在系统范围内唯一,不过这种唯一是相对的,当一个进程消亡后,它的ID可能被重用。不过大多数Unix系统实现延迟重用算法,防止将新进程误认为是使用同一ID的某个已终止的进程,下面这......
  • 下载 Microsoft Office 光盘映像(ISO 文件)
    Office365 ProPlus(Retail版) 简体中文:32/64位下载:https://officecdn.microsoft.com/sg/492350f6-3a01-4f97-b9c0-c7c6ddf67d60/media/zh-CN/O365ProPlusRetail.imgOffice2021 ProPlus(Retail版) 简体中文:32/64位下载:http://officecdn.microsoft.com/pr/492350f6-3a01-4f......
  • 前端学习-UI框架学习-Bootstrap5-008-信息提示框
    菜鸟教程链接提示框-基础颜色提示框可以使用.alert类,后面加上.alert-success,.alert-info,.alert-warning,.alert-danger,.alert-primary,.alert-secondary,.alert-light或.alert-dark类来实现:提示框添加链接提示框中在链接的标签上添加alert-link类来设置匹......
  • 017、夏日南亭怀辛大
    017、夏日南亭怀辛大唐●孟浩然山光忽西落,池月渐东上。散发乘夕凉,开轩卧闲敞。荷风送香气,竹露滴清响。欲取鸣琴弹,恨无知音赏。感此怀故人,中宵劳梦想。 【现代诗意译】南亭夏日想念辛大老友 山上的夕阳余光向西徐徐落下,池塘上明月慢慢从东方升起。 我披散着头发在......
  • Android 手势相关(一)
    Android手势相关(一)本篇文章主要记录下android手势相关的一些内容.Android提供了一套强大的手势识别框架,可以用来检测和处理用户的手势操作.1:手势识别Android提供了GestureDetector类来识别手势,通过GestureDetector可以检测用户的滑动,长按,双击等手势操作.2:手势......
  • 10天【代码随想录算法训练营34期】 第五章 栈与队列part01(● 232.用栈实现队列 ● 22
    232.用栈实现队列classMyQueue:def__init__(self):self.queue=[]self.size=0defpush(self,x:int)->None:self.queue.append(x)self.size+=1defpop(self)->int:self.size-=1retur......
  • anaconda 教程
    官网下载地址:https://www.anaconda.com/download/path环境变量:Anaconda3Anaconda3/ScriptsAnaconda3/Library/bin创建虚拟环境condacreate-n<env-name>[python=x.x]激活退出移除拷贝虚拟环境condaactive<env-name>condadeactivate<env-name>condaremove-......
  • 美团一面:项目中使用过Redis吗?我说用Redis做缓存。他对我哦了一声
    引言Redis,作为一种开源的、基于内存且支持持久化的键值存储系统,以其卓越的性能、丰富灵活的数据结构和高度可扩展性在全球范围内广受欢迎。Redis不仅提供了一种简单直观的方式来存储和检索数据,更因其支持数据结构如字符串、哈希、列表、集合、有序集合等多种类型,使得其在众多场景......