实例:
client
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> const int MAXLINE = 100; void str_cli(int sockfd) { char recvline[MAXLINE]; string str; getline(cin, str); while (!str.empty()) { send(sockfd, str.c_str(), str.size(), 0); if (recv(sockfd, recvline, MAXLINE, 0) != -1) { cout << "receive from server:" << recvline << endl; } getline(cin, str); } } int main() { int sockfd; struct sockaddr_in servaddr; sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(8000); inet_pton(AF_INET, "10.3.17.75", &servaddr.sin_addr); connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); str_cli(sockfd); exit(0); }
server
#include <sys/socket.h> #include <netinet/in.h> void str_echo(int sockfd) { size_t n; char line[MAXLINE]; while(true) { if ((n = recv(sockfd, line, MAXLINE, 0)) == 0) return; cout << "from client:" << line << endl; send(sockfd, line, n, 0); } } int main(int argc, char** argv) { int listenfd, connfd; socklen_t clilen; struct sockaddr_in cliaddr, servaddr; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(8000); bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); listen(listenfd, 0); while (true) { clilen = sizeof(cliaddr); connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &clilen); if ( 0 == fork() ) { close(listenfd); str_echo(connfd); exit(0); } close(connfd); } }