简单实现客户端服务端互联通信
Posted cyyljw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单实现客户端服务端互联通信相关的知识,希望对你有一定的参考价值。
/*服务端程序*/
#include <stdio.h>
#include <stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include <string.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
int main(void)
{
int sockfd,ret,newfd;
int readlen;
int theirlen;
char recv[100]={0};
struct sockaddr_in myaddr;
struct sockaddr_in theiraddr;
if((sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("socket failed(%s)
", strerror(errno));
exit(0);
}
memset(&myaddr,0,sizeof(myaddr));
myaddr.sin_family=AF_INET;
myaddr.sin_port =htons(3490);
myaddr.sin_addr.s_addr=htonl(INADDR_ANY);
if((ret=bind(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr))) < 0)
{
printf("bind failed
");
exit(0);
}
if((ret=listen(sockfd,10)) < 0)
{
printf("listen failed
");
exit(0);
}
theirlen=sizeof(theiraddr);
if((newfd=accept(sockfd,(struct sockaddr *)&theiraddr,&theirlen)) < 0)
{
printf("accept failed
");
exit(0);
}
while(1)
{
memset(recv,0,sizeof(recv));
readlen=read(newfd,recv,sizeof(recv));
fputs(recv,stdout);
write(newfd,recv,readlen);
}
close(newfd);
close(sockfd);
return 0;
}
/*客户端程序*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
int main(void)
{
int sockfd,ret;
int readlen;
char send[100]={0};
char recv[100]={0};
struct sockaddr_in myaddr;
if((sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("socket failed
");
exit(1);
}
memset(&myaddr,0,sizeof(myaddr));
myaddr.sin_family=AF_INET;
myaddr.sin_port =htons(3490);
myaddr.sin_addr.s_addr=inet_addr("192.168.1.110");
if((ret=connect(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr))) < 0)
{
printf("connect failed
");
exit(1);
}
while(1)
{
memset(recv,0,sizeof(recv));
memset(send,0,sizeof(send));
if(fgets(send,sizeof(send),stdin) !=NULL)
{
write(sockfd,send,sizeof(send));
read(sockfd,recv,sizeof(recv));
fputs(recv,stdout);
}
}
close(sockfd);
return 0;
}
代码完整,可直运行
以上是关于简单实现客户端服务端互联通信的主要内容,如果未能解决你的问题,请参考以下文章