TCP通信程序

本文详细介绍了使用C语言实现的TCP全双工通信过程,包括发送端的socket、connect、send、recv和close操作,以及接收端的socket、bind、listen、accept和数据传输过程。
摘要由CSDN通过智能技术生成
#发端
#include "head.h"
	
int main(void)
{	
	int sockfd = 0;
	ssize_t nsize =0;
	struct sockaddr_in recvaddr;
	char tmpbuff[1024];
	int ret = 0;
	int fd = 0; int nret = 0;
	
	sockfd = socket(AF_INET,SOCK_STREAM,0);  /* 流式套接字 */
	if(-1==sockfd)
	{
		perror("fail to socket");
		return -1;
	}
	recvaddr.sin_family =AF_INET;
	recvaddr.sin_port = htons(50000);
	recvaddr.sin_addr.s_addr = inet_addr("192.168.1.156");
	
	ret = connect(sockfd,(struct sockaddr *)&recvaddr,sizeof(recvaddr));
	if(-1==ret)
	{
		perror("fail to connect");
		return -1;
	}

	printf("请输入发送文件名");
	gets(tmpbuff);
	nsize = send(sockfd,tmpbuff,strlen(tmpbuff),0);
	if(-1==nsize)
	{
		perror("fail to send");
		return -1;
	}
	sleep(1);
	fd = open(tmpbuff,O_RDONLY);
	while(1)
	{
		memset(tmpbuff,0,sizeof(tmpbuff));
		nret = read(fd,tmpbuff,sizeof(tmpbuff));
		if(nret<=0)
		{
			break;
		}
		nsize = send(sockfd,tmpbuff,nret,0);
	}
	
	close(fd);	
	close(sockfd);
	return 0;
}	
//接收端
#include "head.h"
	
int main(void)
{	
	int sockfd = 0;//socket->bind->listen->accept->recv->close
	ssize_t nsize =0;
	struct sockaddr_in recvaddr;
	char tmpbuff[1024];
	int ret = 0; int confd = 0;
	int fd = 0; 
	
	sockfd = socket(AF_INET,SOCK_STREAM,0);  /* 流式套接字 */
	if(-1==sockfd)
	{
		perror("fail to socket");
		return -1;
	}
	recvaddr.sin_family =AF_INET;
	recvaddr.sin_port = htons(50000);
	recvaddr.sin_addr.s_addr = inet_addr("192.168.1.156");/*INADDR_ANY*/
	ret = bind(sockfd,(struct sockaddr *)&recvaddr,sizeof(recvaddr));

	ret =  listen(sockfd,10);

	confd = accept(sockfd,NULL,NULL);
	
	nsize = recv(confd,tmpbuff,sizeof(tmpbuff),0);

	fd = open(tmpbuff,O_WRONLY|O_CREAT|O_TRUNC,0664);
	while(1)
	{
		nsize = recv(confd,tmpbuff,sizeof(tmpbuff),0);
		if(nsize == 0)
		{
			break;
		}
		write(fd,tmpbuff,nsize);
	}

	close(fd);close(confd);
	
	close(sockfd);
	return 0;
}

    上述代码为 TCP全双工通信

TCP发端:
    socket 
    connect 
    send
    recv 
    close 

TCP收端:
    socket 
    bind 
    listen 
    accept //有阻塞功能
    send 
    recv 
    close 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值