参考《TCP/IP网络编程第四章》
服务器端代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using std::cout;
using std::cin;
using std::string;
using std::endl;
#define BUF_SIZE 1024
#define SERVER_IP "127.0.0.1" // 指定服务端的IP
#define SERVER_PORT 9190 // 指定服务端的port
int main() {
int serv_sock, clnt_sock;
char message[BUF_SIZE];
int str_len, i;
struct sockaddr_in serv_adr, clnt_adr;
socklen_t clnt_adt_sz;
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock == -1) cout <<"Create socket error" << errno << ": " << strerror(errno) << endl;
bzero(&serv_adr, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_adr.sin_port = htons(SERVER_PORT);
if(bind(serv_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) == -1)
cout << "Bind error" << errno << ": " << strerror(errno) << endl;
if(listen(serv_sock, 5) == -1)
cout << "Listen error" << errno << ": " << strerror(errno) << endl;
clnt_adt_sz = sizeof(clnt_adr);
//调用 5 次 accept 函数,共为 5 个客户端提供服务
for(int i = 0; i != 5; ++i) {
clnt_sock = accept(serv_sock, (struct sockaddr*) &clnt_adr, &clnt_adt_sz);
if(clnt_sock == -1)
cout << "Accept error" << errno << ": " << strerror(errno) << endl;
else
cout << "Connect client" << i + 1 << endl;
while((str_len = read(clnt_sock, message, BUF_SIZE) != 0))
write(clnt_sock, message, str_len);
close(clnt_sock);
}
close(serv_sock);
return 0;
}
客户端代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using std::cout;
using std::cin;
using std::string;
using std::endl;
#define BUFFSIZE 1024
#define SERVER_IP "127.0.0.1" // 指定服务端的IP
#define SERVER_PORT 9190 // 指定服务端的port
int main()
{
int sock;
char message[BUFFSIZE];
int str_len;
struct sockaddr_in serv_adr;
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1) cout << "socket() error" << endl;
bzero(&serv_adr, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = inet_addr(SERVER_IP);
serv_adr.sin_port = htons(SERVER_PORT);
if(connect(sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) == -1)
cout << "connect() error: " << errno << " " << strerror(errno) << endl;
else
cout << "connected............" << endl;
while(1)
{
cout << "Input message(Q to quit): " << endl;
cin >> message;
if(!strcmp(message, "q") || !strcmp(message, "Q"))
break;
write(sock, message, strlen(message));
str_len = read(sock, message, BUFFSIZE - 1);
message[str_len] = 0;
cout << "Message from server:" << message << endl;
}
close(sock);
return 0;
}