【C C++服务器开发】具备丰富功能和可以同时响应多个客服端的服务器_c+

avatar
作者
猴君
阅读量:0

serv_addr.sin_family = AF_INET; //使用IPv4地址
serv_addr.sin_addr.s_addr = inet_addr(“127.0.0.1”); //具体的IP地址
serv_addr.sin_port = htons(1234); //端口
bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

//进入监听状态,等待用户发起请求
listen(serv_sock, 20);

char bufferrev[100];
memset(bufferrev, 0x00, sizeof(bufferrev));
char* buffersnd;

while(1) {

//接收客户端请求
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size = sizeof(clnt_addr);
int clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);

int len = read(clnt_sock, bufferrev, 100-1);
printf(“receive data: %s\n”, bufferrev);

if (strcmp(bufferrev, “wuhan”) == 0) {
strcpy(buffersnd, “you want know wuhan!”);
} else if (strcmp(bufferrev, “guangzhou”) == 0) {
strcpy(buffersnd, “you want know guangzhou!”);
} else if (strcmp(bufferrev, “shenzhen”) == 0) {
strcpy(buffersnd, “you want know shenzhen!”);
} else if (strcmp(bufferrev, “shagnhai”) == 0) {
strcpy(buffersnd, “you want know shanghai!”);
} else {strcpy(buffersnd, “no data about that!”);}

//向客户端发送数据,将从客户端接收的数据反送回去
printf(“server send data to client!\n”);
write(clnt_sock, buffersnd, sizeof(buffersnd));

//重置缓存区
memset(bufferrev, 0x00, sizeof(bufferrev));
memset(buffersnd, 0x00, sizeof(buffersnd));

//关闭客户端套接字
close(clnt_sock);

}

//关闭服务端套接字
close(serv_sock);
return 0;
}

client.cpp

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main(){

//向服务器(特定的IP和端口)发起请求
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr)); //每个字节都用0填充
serv_addr.sin_family = AF_INET; //使用IPv4地址
serv_addr.sin_addr.s_addr = inet_addr(“127.0.0.1”); //具体的IP地址
serv_addr.sin_port = htons(1234); //端口

char bufSend[100] = {0};
char bufRecv[100] = {0};

while(1) {
//创建套接字
int sock = socket(AF_INET, SOCK_STREAM, 0);

connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

//获取用户输入的字符串并发送给服务器
printf(“please choose a city you want know!\n”);
printf(“wuhan guangzhou shanghai shenzhen\n”);
printf(“Input a city name: “);
scanf(”%s”, bufSend);
//gets(bufSend);

write(sock, bufSend

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!