要实现在一个线程里建立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);
}