嵌入式-TCP一对一双向通信

TCP一对一双向通信

服务器:

#include "/home/ubuntu/myhead.h"

int con_fd = -1;

void *recv_to_cilent(void *arg)
{
	
	char *buf = malloc(100);
	while(1)
	{
		memset(buf,0,100);
		recv(con_fd,buf,100,0);
		printf("from cilent:%s\n",buf);
		
	}
}

//一对一双向
int main(int argc,char **argv)
{
	int sock_fd = socket(AF_INET,SOCK_STREAM,0);
	
	struct sockaddr_in serve, cilent;
	
	serve.sin_family = AF_INET;
	serve.sin_port = htons(atoi(argv[2]));
	serve.sin_addr.s_addr = inet_addr(argv[1]);
	
	socklen_t serve_len = sizeof(serve);  
	socklen_t cilent_len =sizeof(cilent); 
	
	bind(sock_fd,&serve,serve_len);
	
	listen(sock_fd,4);
	
	printf("等待连接.....\n");
	con_fd = accept(sock_fd,&cilent,&cilent_len);
	printf("连接成功!!!!\n");
	
	pthread_t tid;
	pthread_create(&tid,NULL, recv_to_cilent,NULL);
	
	
	char *buf = malloc(100);
	while(1)
	{
		memset(buf,0,100);
		fgets(buf,100,stdin);
		send(con_fd,buf,100,0);
	}
}

客户端:

#include "/home/ubuntu/myhead.h"

int sock_fd = -1;

void *cilent_to_serve(void *arg)
{
	char *buf = malloc(100);
	while(1)
	{
		memset(buf,0,100);
		fgets(buf,100,stdin);
		send(sock_fd,buf,100,0);
	}
}



int main(int argc,char **argv)
{
	sock_fd = socket(AF_INET,SOCK_STREAM,0);
	
	struct sockaddr_in serve, cilent;
	
	serve.sin_family = AF_INET;
	serve.sin_port = htons(atoi(argv[2]));
	serve.sin_addr.s_addr = inet_addr(argv[1]);
	
	socklen_t serve_len = sizeof(serve);  
	socklen_t cilent_len =sizeof(cilent); 
	
	bind(sock_fd,&serve,serve_len);
	
	connect(sock_fd,&serve,serve_len);
	
	pthread_t tid;
	pthread_create(&tid,NULL, cilent_to_serve,NULL);
	
	char *buf = malloc(100);
	while(1)
	{
		memset(buf,0,100);
		recv(sock_fd,buf,100,0);
		printf("from serve:%s\n",buf);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值