linux下 在同一个线程建立TCP连接

要实现在一个线程里建立TCP连接,需要注意accept应在connect之后,所以我将accept放在了tcp_client里。这样,才能得到accept返回的fd,从而进行read

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

int _fd;
static int sock_fd[2];

/* tcp server端 */
void tcp_server()
{
    sock_fd[0] = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr1;
    addr1.sin_family = AF_INET;
    addr1.sin_port = htons(32143);
    addr1.sin_addr.s_addr = INADDR_ANY;
    
    if(0 > bind(sock_fd[0], (struct sockaddr*)&addr1, sizeof(sockaddr)))
        printf("bind error\n");
        
    if(0 > listen(sock_fd[0], 5))
        printf("listen error\n");
}

/* tcp client端 */
void tcp_client()
{
    sock_fd[1] = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr1;
    addr1.sin_family = AF_INET;
    addr1.sin_port = htons(32143);
    addr1.sin_addr.s_addr = INADDR_ANY;

    if(0 > connect(sock_fd[1], (struct sockaddr*)&addr1, sizeof(sockaddr)))
        printf("connect error");
    else
        printf("connect success\n");
	
	/* accept没放在server端的代码里 */
    sockaddr_in addr2;
    socklen_t len = sizeof(sockaddr);
    _fd = accept(sock_fd[0], (struct sockaddr*)&addr2, &len);
    char cip[16];
    inet_ntop(AF_INET, &addr2.sin_addr.s_addr, cip, sizeof(cip));
    unsigned short cport = ntohs(addr2.sin_port);
    printf("client ip is %s,port is %d\n", cip, cport);
}

void* thread1_func(void*)
{
    printf("enter thread 1 \n");
    char buf[1024];
    while(1)
    {
        int ret = 0;
        ret = read(_fd, buf, 1024);
        if(ret > 0)
            printf("recv %d--> %s\n", ret, buf);
    }
}

void* thread2_func(void*)
{
    printf("enter thread 2 \n");
    while(1)
    {
        int ret = write(sock_fd[1], "hello", sizeof("hello"));
        printf("send %d\n", ret);
        sleep(5);
    }
}

int main()
{
	/* 在主线程完成TCP的连接 */
    tcp_server();
    tcp_client();
    
    /* 在子线程t1、t2中完成收发数据 */
    pthread_t t1, t2;
    pthread_create(&t1, NULL, thread1_func, NULL);
    pthread_create(&t2, NULL, thread2_func, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值