Skip to content

Commit

Permalink
use multithread for client input
Browse files Browse the repository at this point in the history
  • Loading branch information
navining committed Apr 19, 2020
1 parent 1e00753 commit ed07e29
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 13 deletions.
46 changes: 36 additions & 10 deletions Zeus-Client/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <WinSock2.h>
#include <windows.h>
#include <iostream>
#include <thread>
//#pragma comment(lib, "ws2_32.lib")

using namespace std;
Expand Down Expand Up @@ -106,6 +107,33 @@ int processor(SOCKET _cli) {
return 0;
}

bool g_exit = false;

void cmdThread(SOCKET _sock) {
char cmdBuf[256] = {};
while (!g_exit) {
scanf("%s", cmdBuf);
if (0 == strcmp(cmdBuf, "quit")) {
cout << "Client exits" << endl;
g_exit = true;
}
else if (0 == strcmp(cmdBuf, "login")) {
Login _login;
strcpy(_login.username, "Navi");
strcpy(_login.password, "123456");
send(_sock, (const char *)&_login, sizeof(Login), 0);
}
else if (0 == strcmp(cmdBuf, "logout")) {
Logout _logout;
strcpy(_logout.username, "Navi");
send(_sock, (const char *)&_logout, sizeof(Logout), 0);
}
else {
cout << "Invalid input!" << endl;
}
}
}

int main() {
WORD version = MAKEWORD(2, 2);
WSADATA data;
Expand Down Expand Up @@ -133,12 +161,16 @@ int main() {
cout << "Connect - Success" << endl;
}

while (true) {
// New thread
thread _cmd(cmdThread, _sock);
_cmd.detach();

while (!g_exit) {
// Select
fd_set fdRead;
FD_ZERO(&fdRead);
FD_SET(_sock, &fdRead);
timeval t = { 0, 5e5 };
timeval t = { 0, 0 };
int ret = select(_sock, &fdRead, NULL, NULL, &t);

if (ret < 0) {
Expand All @@ -154,16 +186,10 @@ int main() {
break;
}
}

// Handle other services
cout << "Other services..." << endl;
Login _login;
strcpy(_login.username, "Navi");
strcpy(_login.password, "123456");
send(_sock, (const char *)&_login, sizeof(Login), 0);
Sleep(500);
}

// Handle other services
//cout << "Other services..." << endl;

// Close
closesocket(_sock);
Expand Down
6 changes: 3 additions & 3 deletions Zeus-Server/server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ int processor(SOCKET _cli) {
int recvlen = recv(_cli, recvBuf, sizeof(Header), 0);
Header *_header = (Header *)recvBuf;
if (recvlen <= 0) {
cout << "Client " << _cli << " quits" << endl;
cout << "Client " << _cli << " exits" << endl;
return -1;
}

Expand Down Expand Up @@ -167,7 +167,7 @@ int main() {
FD_SET(g_clients[n], &fdRead);
}

timeval t = {0, 5e5};
timeval t = {0, 0};
int ret = select(_sock + 1, &fdRead, &fdWrite, &fdExcept, &t);

if (ret < 0) {
Expand Down Expand Up @@ -209,7 +209,7 @@ int main() {
}

// Handle other services
cout << "Other services..." << endl;
//cout << "Other services..." << endl;
}

// Close
Expand Down

0 comments on commit ed07e29

Please sign in to comment.