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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <iterator> #include <unistd.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h>
using namespace std;
int main(int argc, char *argv[]) { if (argc != 3) { cout << "Usage:\n\t./Client <服务端IP> <服务端端口>\n"; return -1; }
cout << "连接到 " << argv[1] << ":" << argv[2] << endl;
int socketFd = socket(AF_INET, SOCK_STREAM, 0); if (socketFd == -1) { perror("socket"); return -1; }
struct hostent* h; if ((h = gethostbyname(argv[1])) == 0) { perror("gethostbyname"); close(socketFd); return -1; } struct sockaddr_in serverAddr; memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; memcpy(&serverAddr.sin_addr, h->h_addr, h->h_length); serverAddr.sin_port = htons(atoi(argv[2])); if (connect(socketFd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) { perror("connect"); close(socketFd); return -1; }
char buffer[1024]; for (int i = 0; i < 3; i++) { int iret; memset(buffer, 0, sizeof(buffer)); sprintf(buffer, "这是第%d条报文", i + 1);
if ((iret = send(socketFd, buffer, strlen(buffer), 0)) <= 0) { perror("send"); break; } cout << "发送: " << buffer << endl;
memset(buffer, 0, sizeof(buffer)); if ((iret = recv(socketFd, buffer, sizeof(buffer), 0)) <= 0) { cout << "iret=" << iret << endl; break; } cout << "接收: " << buffer << endl; } close(socketFd); return 0; }
|