# socket通信-多线程

该博客介绍了如何在Linux环境中使用Java通过多线程进行socket通信。每个线程负责不同的连接,并通过传递唯一标识来区分,实现了多个连接的同时处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#! https://zhuanlan.zhihu.com/p/538247988

socket通信-多线程

使用多线程完成,对每个线程传递对应的位次号,虽然每个线程都调用同一个函数,但是函数中接收函数的文件描述符不同,通过设置数组实现。

static void *new_thread_start(void *arg)
{
    int ret, thread_count=0;
    char ip_str[20] = {0};
    char recvbuf[512];

    thread_count = *((int *)arg);

    //pthread_mutex_lock(&mutex);

    printf("There is client access..\n");
    printf("This threadID=%lu \n", pthread_self());
    printf("There is client%d access..\n", thread_count);
    inet_ntop(AF_INET, &client_addr.sin_addr, ip_str, sizeof(ip_str));
    printf("The IP address of the client host is: %s\n", ip_str);
    printf("The port number of the client process is: %d\n", client_addr.sin_port);

    for ( ; ; )
    {
        /* code */
        memset(recvbuf, 0x0, sizeof(recvbuf));

        ret = recv(connfd[thread_count], recvbuf, sizeof(recvbuf), 0);
        if(0 >= ret)
        {
            perror("recv error");
            close(connfd[thread_count]);
            break;
        }
        printf("from client%d:%s\n", thread_count ,recvbuf);

        if(0 == strncmp("exit", recvbuf, 4))
        {
            printf("server exit...\n");
            close(connfd[thread_count]);
            break;
        }
    }

    close(sockfd);
    pthread_exit(NULL);
    exit(EXIT_SUCCESS);

    //pthread_mutex_unlock(&mutex);
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值