Socket 网络通讯
主要内容:socket基于tcp建立通讯。建立通过简述,待续。
- server
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<unistd.h>#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int main()
{int sock_id,client_id;sock_id=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(sock_id==-1){cout<<"create socket error"<<endl;exit(0);}//IPV4struct sockaddr_in seraddr;seraddr.sin_family=AF_INET;seraddr.sin_port=htons(8900);//seraddr.sin_addr.s_addr=htonl(INADDR_ANY);if(inet_pton(AF_INET,"127.0.0.1",&seraddr.sin_addr)<=0)cout<<"inet_pton error"<<endl;//bindif(bind(sock_id,(sockaddr*)&seraddr,sizeof(seraddr))==-1){cout<<"bind error"<<endl;exit(0);}//listenif(listen(sock_id,10)==-1){cout<<"listen error"<<endl;exit(0);}cout<<"wait connect"<<endl;int len=0;char buf[4096];const int MAX_LINE=4096;while(1){client_id=accept(sock_id,(sockaddr*)NULL,NULL);if(client_id==-1){cout<<"accpet error"<<endl;continue;}//recvlen=recv(client_id,buf,MAX_LINE,0);buf[len]='\0';cout<<"recv:"<<endl<<buf<<endl;if(fork()==0){cout<<"echo"<<endl;//收到消息后有子进程处理if(send(client_id,"echo\n",5,0)==-1)cout<<"send error"<<endl;exit(0);}close(client_id);}close(sock_id);return 0;
}
- client
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<errno.h>#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
using namespace std;
int main()
{int sock_id;sock_id=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(sock_id==-1){cout<<"create socket error"<<endl;exit(0);//为什么不用return 0;}//IPV4struct sockaddr_in seraddr;seraddr.sin_family=AF_INET;seraddr.sin_port=htons(8900);if((inet_pton(AF_INET,"127.0.0.1",&seraddr.sin_addr))==0){cout<<"inet_pton error"<<endl;exit(0);}if(connect(sock_id,(struct sockaddr*)&seraddr,sizeof(seraddr))==-1){cout<<"connect d error:"<<strerror(errno)<<endl;exit(0);}int len=0;char buf[4096];const int MAX_LINE=4096;strcpy(buf,"hello server from client");cout<<"sending"<<endl;if(send(sock_id,buf,strlen(buf)+1,0)==-1){cout<<"send error"<<endl;close(sock_id);exit(0);}len=recv(sock_id,buf,MAX_LINE,0);buf[len]='\0';cout<<"recv:"<<endl<<buf;close(sock_id);return 0;
}