1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include <iostream> #include <arpa/inet.h> #include <unistd.h> #include <cstring> int main() { int soct1=socket(AF_INET,SOCK_STREAM,0); if(soct1 == -1) { std::cerr<<"create socket failed!"<<std::endl; return -1; } struct sockaddr_in host; host.sin_family = AF_INET; host.sin_port = htons(12345); host.sin_addr.s_addr = INADDR_ANY; int flag=connect(soct1,(sockaddr*)&host,sizeof(sockaddr)); if (flag==-1) { std::cerr<<"connect failed"<<std::endl; return -1; } char buffer[1024]; while (true) { sprintf(buffer,"hello server!"); send(soct1,buffer,strlen(buffer)+1,0); memset(buffer,0,sizeof(buffer)); int rec1=recv(soct1,buffer,sizeof(buffer),0); if (rec1>0) { std::cerr<<buffer<<std::endl; } else if (rec1=0) { std::cerr<<"server disconnect"<<std::endl; } else { std::cerr<<"send failed"<<std::endl; } sleep(1); } close(soct1); }
|