#发端
#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