当前位置:   article > 正文

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

c++ socket服务器接受多个客户端

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, bufSen

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/973669
推荐阅读
  

闽ICP备14008679号