tcp客户端主线程发送,接收消息单独一个线程

本文介绍了一个使用C语言实现的网络通信程序,通过主线程发送消息,子线程接收消息,以避免阻塞,确保收发互不影响。主要展示了socket编程和多线程技术的应用。
摘要由CSDN通过智能技术生成

为了防止接收消息时阻塞发送消息,故提出主线程发送消息,子线程用来接收消息(接收频次较低),以此来达到收发互不影响

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <unistd.h>  
#include <pthread.h>  
#include <signal.h>  
#include <sys/types.h>  
#include <sys/socket.h>  
#include <netinet/in.h>  
#include <arpa/inet.h>  
  
#define SERVER_IP "127.0.0.1"  
#define SERVER_PORT 8080  
#define BUFFER_SIZE 1024  
  
void *receive_thread(void *arg) {  
    int sockfd = *(int *)arg;  
    char buffer[BUFFER_SIZE];  
    ssize_t bytes_read;  
  
    while (1) {  
        bytes_read = recv(sockfd, buffer, BUFFER_SIZE - 1, 0);  
        if (bytes_read > 0) {  
            buffer[bytes_read] = '\0'; // Null-terminate the string  
            printf("Received: %s\n", buffer);  
        } else if (bytes_read == 0) {  
            printf("Server closed the connection\n");  
            break;  
        } else {  
            perror("recv failed");  
            break;  
        }  
    }  
  
    close(sockfd);  
    pthread_exit(NULL);  
}  
  
int main() {  
    int sockfd;  
    struct sockaddr_in server_addr;  
    pthread_t receive_tid;  
    int result;  
  
    // Create socket  
    sockfd = socket(AF_INET, SOCK_STREAM, 0);  
    if (sockfd < 0) {  
        perror("socket creation failed");  
        return EXIT_FAILURE;  
    }  
  
    // Set server address  
    memset(&server_addr, 0, sizeof(server_addr));  
    server_addr.sin_family = AF_INET;  
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);  
    server_addr.sin_port = htons(SERVER_PORT);  
  
    // Connect to server  
    if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {  
        perror("connection failed");  
        return EXIT_FAILURE;  
    }  
  
    printf("Connected to server\n");  
  
    // Create receive thread  
    result = pthread_create(&receive_tid, NULL, receive_thread, (void *)&sockfd);  
    if (result != 0) {  
        perror("pthread_create failed");  
        close(sockfd);  
        return EXIT_FAILURE;  
    }  
  
    // Main thread sending messages  
    char message[] = "Hello from client!";  
    while (1) {  
        send(sockfd, message, strlen(message), 0);  
        printf("Sent: %s\n", message);  
        sleep(1); // Send a message every second  
    }  
  
    // Wait for receive thread to finish (this is optional if the main thread will run forever)  
    pthread_join(receive_tid, NULL);  
  
    close(sockfd);  
    return 0;  
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会C语言的男孩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值