我正在编写一个服务器/客户端通信系统,客户端请求登录服务器并可以请求查看其他客户端的在线状态。我可以使客户端登录正常,但是当我尝试登录(成功)然后发送请求其他客户端信息的另一个数据包时,服务器不会收到该数据包。
服务器的主要部分,而不是从bind Server开始的技术连接:
Users client[2]; //I intialized them already
//Bind
bind(WelcomeSocket, (sockaddr*)&SvrAddr, sizeof(SvrAddr));
//listening
listen(WelcomeSocket, 5);
//temp users
Users temp;
//while loop for the connection
while (1) {
ConnectionSocket = accept(WelcomeSocket, NULL, NULL);
if (recv(ConnectionSocket, RxBuffer, sizeof(RxBuffer), 0))
cout << "WORKEDDDDDDDD" << endl;
memcpy(&temp, RxBuffer, sizeof(struct Users));
cout << temp.message << temp.userName << endl << endl;
//check which message type is being sent
switch(temp.message) {
//if message type 1
case 1 :
for (int i = 0; i < 2; i++) {
//if receieved username matches with any username in the database
if (strcmp(temp.userName, client[i].userName) == 0) {
//assign the recieved users information to the matched one in database
strcpy(client[i].userName, temp.userName);
client[i].online = true;
client[i].message = 2;
cout << client[i].userName << endl << client[i].online << endl;
//send the acknowledgement packet
send(ConnectionSocket, (char *)&client[i], sizeof(struct Users), 0);
}
}
closesocket(ConnectionSocket);
break;
//if message type 3
case 3 :
cout << "3";
break;
default :
break;
}
}
closesocket(ConnectionSocket);
WSACleanup();
}
客户:
connect(ClientSocket, (sockaddr*)&SvrAddr, sizeof(SvrAddr));
//cout << "Name: ";
//cin >> login;
//Send request to login
int log;
char * name = new char[128];
char * request = new char[128];
Users client;
Users talkto;
cout << "To login press (1). ";
cin >> log;
flushall();
if (log == 1) {
cout << "Username : ";
cin.getline(name, 128, '\n');
flushall();
//Set client login info
strcpy(client.userName, name);
client.message = 1;
send(ClientSocket, (char *)&client, sizeof(struct Users), 0);
//Recieve acknowledgement
recv(ClientSocket, RxBuffer, sizeof(RxBuffer), 0);
//create temp users
Users temp;
memcpy(&temp, RxBuffer, sizeof(struct Users));
if (temp.message == 2) {
cout << "Enter user for user information: ";
cin.getline(talkto.userName, 128, '\n');
flushall();
talkto.message = 3;
//send request for user information packet
if (send(ClientSocket, (char *)&talkto, sizeof(struct Users), 0))
cout << "SENDT" << endl;
}
//cout << temp.userName << endl << temp.online << endl << temp.message;
closesocket(ClientSocket);
WSACleanup();
}
用户的结构
struct Users {
int message;
char userName[50];
char ipAddress[50];
int PortNumber;
bool online;
};
不确定为什么它不会多次接收信息
答案 0 :(得分:0)
对于每个客户端连接,您的服务器执行accept-recv-send-closesocket。周期。
服务器处理第一个数据包后,将关闭与客户端的连接。您需要在客户端发送每个数据包之前建立新连接(但这可能会使您的登录过程无效)或使服务器能够维持多个并发客户端连接在无限循环中轮询它们,可能在单独的线程中(一个或多个)。
答案 1 :(得分:0)
ConnectionSocket = accept(WelcomeSocket, NULL, NULL);
你应该把它放在循环之前,而不是在里面,因为accept
函数正在等待另一个客户端,阻止你接收另一个数据包。
此外,当您的recv
调用返回0时,表示连接已关闭,并且它是流的结尾,因此当recv
返回0或某些时,您应该从循环中断意外SOCKET_ERROR
。