Sever.cpp
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
string user[2] = { "lyh0", "lyh1" };
string pwd[2] = { "lyh0", "lyh1" };
string chat[2] = { "Sir, I am here.", "incredible hulk" };
vector
//存放socket的数组
vector
enum cmd
{
cmd_login,
cmd_login_result,
cmd_logout,
cmd_logout_result,
cmd_new_user_join,
cmd_chat,
cmd_error
};
//数据包头
struct DataHeader
{
short datalength;
short cmd;
};
//可以用下面的这种写法,但是不利于衍生成更复杂的消息。
//struct Login
//{
// DataHeader dataheader;
// char username[32];
// char password[32];
//};
//用继承的方式将报头和报体放在一起发送
struct Login : public DataHeader
{
//在构造函数里面初始化
Login()
{
datalength = sizeof(Login);
cmd = cmd_login;
}
char username[32];
char password[32];
};
struct Loginresult : public DataHeader
{
Loginresult()
{
datalength = sizeof(Loginresult);
cmd = cmd_login_result;
result = 0;
}
int result;
};
struct Logout : public DataHeader
{
Logout()
{
datalength = sizeof(Logout);
cmd = cmd_logout;
}
char username[32];
};
struct Logoutresult : public DataHeader
{
Logoutresult()
{
datalength = sizeof(Logoutresult);
cmd = cmd_logout_result;
result = 0;
}
int result;
};
struct Message : public DataHeader
{
Message()
{
datalength = sizeof(Message);
cmd = cmd_chat;
}
char message[256];
};
struct Messageret : public DataHeader
{
Messageret()
{
datalength = sizeof(Messageret);
cmd = cmd_chat;
}
char messageret[256];
};
struct Newuserjoin : public DataHeader
{
Newuserjoin()
{
datalength = sizeof(Newuserjoin);
cmd = cmd_new_user_join;
socketid = 0;
}
int socketid;
};
//把处理请求的逻辑写成一个函数
int Process(SOCKET _clientSock)
{
//用缓冲区接受数据
char recvBuf[1024] = {};
DataHeader* header = (DataHeader*)recvBuf;
//5.1. recv 接收客户端发送的数据
int nlen = recv(_clientSock, recvBuf, sizeof(DataHeader), 0);
if (nlen <= 0)
{
printf("Client %d exit!\n", (int)_clientSock);
return -1;
}
//5.2 send 处理请求, 向客户端发送数据, 用switch判断命令
switch (header->cmd)
{
case cmd_login:
{
//接受客户端输入的账号密码
//使用datalength获取数据
recv(_clientSock, recvBuf + sizeof(DataHeader), header->datalength - sizeof(DataHeader), 0);
Login* login = (Login*)recvBuf;
printf("receive cmd from
Loginresult result;
//防止重复登录
if (0 != loginusr.size())
{
for (int i = 0; i < (int)loginusr.size(); i++)
{
if (loginusr[i] == string(login->username))
{
result.result = 2;
}
}
if (2 == result.result)
{
send(_clientSock, (char*)&result, sizeof(Loginresult), 0);
return 1;
}
}
//判断用户名与密码是否正确的过程
for (int i = 0; i < 2; i++)
{
if (user[i] == string(login->username))
{
if (pwd[i] == string(login->password))
{
loginusr.push_back(user[i]);
printf("it is %d users connect now.\n", (int)loginusr.size());
result.result = 1;
send(_clientSock, (char*)&result, sizeof(Loginresult), 0);
return 1;
}
else
{
result.result = 0;
send(_clientSock, (char*)&result, sizeof(Loginresult), 0);
return 1;
}
}
}
send(_clientSock, (char*)&result, sizeof(Loginresult), 0);
}
break;
case cmd_logout:
{
recv(_clientSock, recvBuf + sizeof(DataHeader), header->datalength - sizeof(DataHeader), 0);
Logout* logout = (Logout*)recvBuf;
Logoutresult result;
//判断用户名是否正确,且用户在已登录的名单中
for (int i = 0; i < (int)loginusr.size(); i++)
{
if (loginusr[i] == string(logout->username))
{
result.result = 1;
printf("receive cmd from
printf("%s logout!\n", logout->username);
loginusr.erase(loginusr.begin() + i);
printf("it is %d users connect now .\n", (int)loginusr.size());
break;
}
}
send(_clientSock, (char*)&result, sizeof(Logoutresult), 0);
}
break;
case cmd_chat:
{
recv(_clientSock, recvBuf + sizeof(DataHeader), header->datalength - sizeof(DataHeader), 0);
printf("receive cmd from
Message* message = (Message*)recvBuf;
Messageret messageret;
if (0 == strcmp(message->message, "friday"))
{
strcpy(messageret.messageret, chat[0].c_str());
//再发消息体
send(_clientSock, (char*)&messageret, sizeof(Messageret), 0);
break;
}
else if (0 == strcmp(message->message, "hulk"))
{
strcpy(messageret.messageret, chat[1].c_str());
//再发消息体
send(_clientSock, (char*)&messageret, sizeof(Messageret), 0);
break;
}
else
{
strcpy(messageret.messageret, "May I help you?");
//再发消息体
send(_clientSock, (char*)&messageret, sizeof(Messageret), 0);
break;
}
}
break;
default:
{
DataHeader head = { 0,cmd_error };
send(_clientSock, (char*)&header, sizeof(DataHeader), 0);
}
break;
}
return 1;
}
int main()
{
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
//用socket API建立简易的服务器端
//1.建立一个socket
SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//2.bind 绑定用于接受客户端连接的网络端口号
sockaddr_in _sin = {};
_sin.sin_family = AF_INET; //用于网络连接的类型,IPv4,与上面定义的一样
_sin.sin_port = htons(4567); //host to net unsigned short,这里要转换一下端口号
//_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //服务器程序绑定的IP地址,纯内网的应用程序可以用127.0.0.1
_sin.sin_addr.S_un.S_addr = INADDR_ANY;
//_sin.sin_addr.S_un.S_addr = INADDR_ANY; //随意什么地址都可以访问
//bind是有可能失败的,端口被占用的时候,所以要判断是否成功
int bindret = bind(_sock, (sockaddr*)&_sin, sizeof(sockaddr_in));
if (SOCKET_ERROR == bindret)
{
printf("ERROR! bind failed !\n");
getchar();
return 1;
}
//3.listen 监听网络端口
//同样的监听也可能失败的,需要加以判断
int listenret = listen(_sock, 3);
if (SOCKET_ERROR == listenret)
{
printf("ERROR! listen failed !\n");
getchar();
return 1;
}
printf("* * * * * * * * * * * * * * * * * * * * * * * * * * * *\n");
printf("* *\n");
printf("* Welcome to the first Socket Sever *\n");
printf("* *\n");
printf("* * * * * * * * * * * * * * * * * * * * * * * * * * * *\n");
//5. send 向客户端发送数据
while (1)
{
//使用select模型
//定义socket集合
fd_set fdRead;
fd_set fdWead;
fd_set fdExp;
//清空
FD_ZERO(&fdRead);
FD_ZERO(&fdWead);
FD_ZERO(&fdExp);
//设置集合
FD_SET(_sock, &fdRead);
FD_SET(_sock, &fdWead);
FD_SET(_sock, &fdExp);
//查询g_clients里面的socket是否有可读要求
for (int i = (int)g_clients.size() - 1; i >= 0 ; i--)
{
FD_SET(g_clients[i], &fdRead);
}
//nfds 是一个整数值,是指集合fd_set中所有socket的范围(是最大的socket值+1),而不是数量。
//而在Windows下可以传入0,Windows下自动处理了。
timeval time = { 1, 0 }; //第一个参数是最大查询时间 单位s,第二个是ms
//select 设置了最后一个参数timeval之后,程序在select处等待最大时间,没有数据读取便会返回。不会一直阻塞在select处。
int selectret = select((int)_sock + 1, &fdRead, &fdWead, &fdExp, &time);
if (selectret < 0)
{
//select小于0就是出错了
printf("select finish..error.\n");
break;
}
if (FD_ISSET(_sock, &fdRead))
{
//清理标志位
FD_CLR(_sock, &fdRead);
//客户端的连接要放在此处执行
//4.accept 等待接受客户端连接
sockaddr_in clientAddr = {}; //远程客户端的地址
int nAddrlen = sizeof(sockaddr_in);
SOCKET _clientSock = INVALID_SOCKET; //接受的客户端是无效的,大规模程序的时候有可能
_clientSock = accept(_sock, (sockaddr*)&clientAddr, &nAddrlen);
if (INVALID_SOCKET == _clientSock)
{
printf("ERROR!, INVALID CLIENT!\n");
}
//有新的客户端加入,群发消息给别的客户端。
for (int i = (int)g_clients.size() - 1; i >= 0; i--)
{
Newuserjoin userjoin; //构造函数里面已经初始化
send(g_clients[i], (char*)&userjoin, sizeof(Newuserjoin), 0);
}
//将新连接的客户端加入进g_clients数组中
g_clients.push_back(_clientSock);
printf("new Client connected :socket = %d IP = %s \n", (int)_clientSock, inet_ntoa(clientAddr.sin_addr));
}
//循环处理客户端数组里面的客户端请求
for (size_t i = 0; i < fdRead.fd_count; i++)
{
if (-1 == Process(fdRead.fd_array[i]))
{
auto iter = find(g_clients.begin(), g_clients.end(), fdRead.fd_array[i]);
if (iter != g_clients.end())
g_clients.erase(iter);
}
}
printf("do other things.............\n");
}
//6.close 关闭socket
//程序结束一定要关闭所有的socket
for (int i = (int)g_clients.size() - 1; i >= 0; i--)
{
closesocket(g_clients[i]);
}
closesocket(_sock);
WSACleanup();
//printf("Client exit !, Sever exit ! \n");
//getchar();
return 0;
}
Client.cpp
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
//或者把winsock2放在Windows前面
#include
#include
#include
//#pragma comment(lib, "ws2_32.lib") //调用了Windows的库,要加载这个静态链接库才能使用
//Windows下才可以这样写,Linux下不可以这样写
enum cmd
{
cmd_login,
cmd_login_result,
cmd_logout,
cmd_logout_result,
cmd_new_user_join,
cmd_chat,
cmd_error
};
//数据包头
struct DataHeader
{
short datalength;
short cmd;
};
//可以用下面的这种写法,但是不利于衍生成更复杂的消息。
//struct Login
//{
// DataHeader dataheader;
// char username[32];
// char password[32];
//};
//用继承的方式将报头和报体放在一起发送
struct Login : public DataHeader
{
//在构造函数里面初始化
Login()
{
datalength = sizeof(Login);
cmd = cmd_login;
}
char username[32];
char password[32];
};
struct Loginresult : public DataHeader
{
Loginresult()
{
datalength = sizeof(Loginresult);
cmd = cmd_login_result;
}
int result;
};
struct Logout : public DataHeader
{
Logout()
{
datalength = sizeof(Logout);
cmd = cmd_logout;
}
char username[32];
};
struct Logoutresult : public DataHeader
{
Logoutresult()
{
datalength = sizeof(Logoutresult);
cmd = cmd_logout_result;
}
int result;
};
struct Message : public DataHeader
{
Message()
{
datalength = sizeof(Message);
cmd = cmd_chat;
}
char message[256];
};
struct Messageret : public DataHeader
{
Messageret()
{
datalength = sizeof(Messageret);
cmd = cmd_chat;
}
char messageret[256];
};
struct Newuserjoin : public DataHeader
{
Newuserjoin()
{
datalength = sizeof(Newuserjoin);
cmd = cmd_new_user_join;
socketid = 0;
}
int socketid;
};
int main()
{
WORD ver = MAKEWORD(2, 2); //版本号
WSADATA dat;
WSAStartup(ver, &dat);
//1. socket 建立一个socket
SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == _sock)
{
printf("ERROR! build socket failed !\n");
getchar();
return 1;
}
//2.connect 连接服务器
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(4567);
_sin.sin_addr.S_un.S_addr = inet_addr("193.112.24.176");
//_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int ret = connect(_sock, (sockaddr*)&_sin, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret)
{
printf("ERROR! connect sever failed !\n");
getchar();
return 1;
}
printf("Successfully connect to the Sever, Please input your cmd.\n");
while (1)
{
//使用select模型
//fd_set fdReads;
//FD_ZERO(&fdReads);
//FD_SET(_sock, &fdReads);
//int selectret = select(_sock, &fdReads, 0, 0, 0);
//if (selectret < 0)
//{
// printf("select error, exit...");
// break;
//}
//if (FD_ISSET(_sock, &fdReads))
//{
// FD_CLR(_sock, &fdReads);
//}
//3. send 发送数据到服务器
char msgbuf[1024] = {};
scanf("%s", msgbuf);
if (0 == strcmp(msgbuf, "exit"))
{
printf("exit client!\n");
break;
}
else if (0 == strcmp(msgbuf, "login"))
{
char username[32] = {};
char password[32] = {};
printf("input your username:\n");
scanf("%s", username);
printf("input the password:\n");
scanf("%s", password);
Login login;
strcpy(login.username, username);
strcpy(login.password, password);
//向服务器发送报体(里面已经包含了报头)
send(_sock, (const char*)&login, sizeof(Login), 0);
//接受服务器返回数据
Loginresult loginret = {};
recv(_sock, (char*)&loginret, sizeof(Loginresult), 0);
//判断返回的结果
//printf("loginresult is : %d \n", loginret.result);
if (loginret.result == 1)
{
printf(" %s login successfully....\n", username);
printf("Friday: Can I help you? Sir.\n");
//登录之后才能进行的操作
while (1)
{
char msg[256] = {};
scanf("%s", msg);
if (0 == strcmp(msg, "exit"))
{
printf("you are welcome.\n");
break;
}
Message message;
strcpy(message.message, msg);
//向服务器发送包体
send(_sock, (const char*)&message, sizeof(Message), 0);
Messageret messageret = {};
recv(_sock, (char*)&messageret, sizeof(Messageret), 0);
//打印收到的消息
printf("Friday : %s\n", messageret.messageret);
}
}
else if (loginret.result == 2)
printf("the %s has already login !\n", username);
else
printf("username or password error, please check.\n");
}
else if (0 == strcmp(msgbuf, "logout"))
{
char username[32] = {};
printf("input the username you want to logout:\n");
scanf("%s", username);
Logout logout;
strcpy(logout.username, username);
//向服务器发送包体
send(_sock, (const char*)&logout, sizeof(Logout), 0);
//接受服务器返回数据
Logoutresult logoutret = {};
recv(_sock, (char*)&logoutret, sizeof(Logoutresult), 0);
//判断返回的结果
//printf("%d\n", logoutret.result);
if (logoutret.result == 1)
printf("%s logout successful !\n", username);
else
printf("%s logout failed ! %s may not login or it is not the legal user.\n", username, username);
}
else
{
printf("Unsupportable cmd, request end.\n");
}
}
//5.close 关闭socket
closesocket(_sock);
WSACleanup();
printf("Client exit !\n");
getchar();
return 0;
}