#include "server.h"
#include "typedef.h"
#include "packet.h"
#include <iostream>
#include <thread>
#include <string>
#include <WS2tcpip.h>
#include <map>
#include <vector>
//using std::cerr;
//using std::cout;
//using std::endl;
using namespace std;
#define SERVER_PORT 1024
#define MSG_BUF_SIZE 1024
#define BUFLEN 1024
std::list<SOCKET> list_sockets;
map<int, SOCKET> map_devSockInfo;
//const uint16 ZYHEAD_LEN = sizeof(ZYHead);
struct packet
{
int _cmd;
int _devNo;
int _type; //报文类型
std::string _data;
SOCKET socket;
};
std::list<packet> list_imgpack;
void InitHead(ZYHead & head, uint32 cmd, uint32 devNo, uint32 len)
{
head.Reset();
head._cmd = cmd;
head._devNo = devNo;
head._dataLen = len;
head._type = 100;
head.Packet();
}
Server::Server()
{
//cout << "Initializing server...\n";
//
winsock_ver = MAKEWORD(2, 2);
addr_len = sizeof(SOCKADDR_IN);
addr_svr.sin_family = AF_INET;
addr_svr.sin_port = ::htons(SERVER_PORT);
addr_svr.sin_addr.S_un.S_addr = ADDR_ANY;
memset(buf_ip, 0, IP_BUF_SIZE);
//WSA启动成功…
ret_val = WSAStartup(winsock_ver, &wsa_data);
if (ret_val != 0)
{
cerr << "WSA failed to start up!Error code: " << ::WSAGetLastError() << "\n";
system("pause");
exit(1);
}
//cout << "WSA started up successfully...\n";
//创建服务器套接字
sock_svr = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock_svr == INVALID_SOCKET)
{
cerr << "Failed to create server socket!Error code: " << ::WSAGetLastError() << "\n";
WSACleanup();
system("pause");
exit(1);
}
//cout << "Server socket created successfully...\n";
// 服务器套接字绑定成功
ret_val = ::bind(sock_svr, (SOCKADDR*)&addr_svr, addr_len);
if (ret_val != 0)
{
cerr << "Failed to bind server socket!Error code: " << ::WSAGetLastError() << "\n";
WSACleanup();
system("pause");
exit(1);
}
//cout << "Server socket bound successfully...\n";
// 服务器套接字开始侦听
ret_val = ::listen(sock_svr, SOMAXCONN);
if (ret_val == SOCKET_ERROR)
{
cerr << "Server socket failed to listen!Error code: " << ::WSAGetLastError() << "\n";
WSACleanup();
system("pause");
exit(1);
}
//cout << "Server socket started to listen...\n";
// 服务器已成功启动..
cout << "Server started successfully..." << endl;
}
Server::~Server()
{
closesocket(sock_svr);
closesocket(sock_clt);
WSACleanup();
cout << "Socket closed..." << endl;
}
// 给特定的设备发送
void sendMessDev(SOCKET s, int devNo, uint32 cmd)
{
string strData;
strData.resize(ZYHEAD_LEN);
ZYHead *head = (ZYHead *)strData.c_str();
InitHead(*head, cmd, devNo, strData.length() - ZYHEAD_LEN);
send(s, strData.c_str(), strData.size(), 0);
cout << "strData: " << strData.c_str() << endl;
}
void sendMessageDev(packet& pt)
{
int nlen = ZYHEAD_LEN + pt._data.size();
ZYHead head;
InitHead(head, pt._cmd, pt._devNo, pt._data.size());
char* pchar = new char[nlen];
memcpy(pchar, &head, ZYHEAD_LEN);
if (pt._data.size())
{
memcpy(pchar + ZYHEAD_LEN, pt._data.c_str(), pt._data.size());
}
send(pt.socket, pchar, nlen, 0);
if (pchar)
{
delete pchar;
pchar = NULL;
}
}
void sendMess() {
while (1) {
std::string input;
std::cin >> input;
//printf("you are send %s", buf);
// send(map_devSockInfo[1], input.c_str(), input.size(), 0);
//sendMessDev(map_devSockInfo[1], 0, 10);
std::list<packet>::iterator it;
for (it = list_imgpack.begin(); it != list_imgpack.end(); ++it)
{
packet pt = *it;
sendMessageDev(pt);
//list_imgpack.remove(pt);
}
list_imgpack.clear();
/*std::list<SOCKET>::iterator it;
for (it = list_sockets.begin(); it != list_sockets.end(); ++it){
send(*it, input.c_str(), input.size(), 0);
}*/
}
}
DWORD WINAPI CreateClient(LPVOID lpParameter);
//
void Server::waitForClient()
{
while (true)
{
sock_clt = accept(sock_svr, (SOCKADDR*)&addr_clt, &addr_len);
if (sock_clt == INVALID_SOCKET)
{
cerr << "Failed to accept client!Error code: " << WSAGetLastError() << "\n";
WSACleanup();
system("pause");
exit(1);
}
list_sockets.push_back(sock_clt);
//map_devSockInfo[1] = sock_clt;
InetNtop(addr_clt.sin_family, &addr_clt,(PWSTR)buf_ip, IP_BUF_SIZE);
cout << "A new client connected...IP sock_svr: " << sock_svr << ", port number: " << ntohs(addr_clt.sin_port) << endl;
h_thread = ::CreateThread(nullptr, 0, CreateClient, (LPVOID)sock_clt, 0, nullptr);
if (h_thread == NULL)
{
cerr << "Failed to create a new thread!Error code: " << ::WSAGetLastError() << "\n";
WSACleanup();
system("pause");
exit(1);
}
CloseHandle(h_thread);
std::thread (sendMess).detach(); //启动发送数据的进程;
}
}
bool GetDevSocketByDevid(int devid,SOCKET& socket)
{
std::map<int, SOCKET>::iterator it = map_devSockInfo.find(devid);
if (it != map_devSockInfo.end())
{
socket = it->second;
return true;
}
return false;
}
int processread(const ZYHead & basehead, char* pdata, const SOCKET & sock_clt)
{
packet pt;
if (basehead._cmd == CMD_APP_READ_IMG_REQ)
{
if (GetDevSocketByDevid(basehead._devNo, pt.socket))
{
pt._cmd = CMD_DEV_READ_IMGREQ;
pt._devNo = basehead._devNo;
pt._type = basehead._type;
if (basehead._dataLen)
{
std::string data(pdata, basehead._dataLen);
pt._data = data;
}
//list_imgpack.push_back(pt);
}
else{
// 处理异常
std::cout << "cant find server dev " << basehead._devNo << std::endl;
}
}
else if (basehead._cmd == CMD_DEV_READ_IMGRESP)
{
if (GetDevSocketByDevid(DEV_NO_APP, pt.socket))
{
pt._cmd = CMD_APP_READ_IMG_RESP;
pt._devNo = basehead._devNo;
pt._type = basehead._type;
if (basehead._dataLen)
{
std::string data(pdata, basehead._dataLen);
pt._data = data;
}
//list_imgpack.push_back(pt);
}
else{
// 处理异常
std::cout << "cant find server dev " << basehead._devNo << std::endl;
}
}
else if (basehead._cmd == CMD_LOGIN)
{
map_devSockInfo[basehead._devNo] = sock_clt;
std::cout << "login server dev " << basehead._devNo << std::endl;
return 0;
}
sendMessageDev(pt);
return 0;
}
void DelMapsocketbydevid(int& devid)
{
map_devSockInfo.erase(devid);
}
void DelMapsocketbysocket(SOCKET& sock_clt)
{
std::map<int, SOCKET>::iterator it;
for (it = map_devSockInfo.begin(); it != map_devSockInfo.end(); ++it)
{
if (it->second == sock_clt)
{
map_devSockInfo.erase(it++);
}
}
}
DWORD WINAPI CreateClient(LPVOID lpParameter)
{
SOCKET sock_clt = (SOCKET)lpParameter;
char buf_msg[MSG_BUF_SIZE];
int ret_val = 0;
int snd_result = 0;
char* pdata = NULL;
ZYHead basehead;
do
{
//memset(buf_msg, 0, MSG_BUF_SIZE);
ret_val = ::recv(sock_clt, (char*)&basehead, ZYHEAD_LEN, MSG_WAITALL);
//********************
// 此处添加对接收的数据包进行解包及分析
if (ret_val < 0)
{
DelMapsocketbysocket(sock_clt);
closesocket(sock_clt);
break;//关闭或者出错
}
if (ret_val != ZYHEAD_LEN)
{
// 读取数据长度不对
DelMapsocketbysocket(sock_clt);
closesocket(sock_clt);
break;
}
if (!basehead.UnPacket())
{
DelMapsocketbysocket(sock_clt);
closesocket(sock_clt);
//"invalid packet ver %d cmd %d len %d", _baseHead._ver, _baseHead._cmd, _baseHead._dataLen);
break;
}
if (basehead._dataLen)
{
pdata = new char[basehead._dataLen];
memset(pdata, 0, basehead._dataLen);
ret_val = ::recv(sock_clt, pdata, basehead._dataLen, MSG_WAITALL);
if (ret_val < 0)
{
delete pdata;
pdata = NULL;
DelMapsocketbysocket(sock_clt);
closesocket(sock_clt);
break;//关闭或者出错
}
if (ret_val != basehead._dataLen)
{
//"invalid len(%d) != data(%d)",ret_val, _baseHead._dataLen);
delete pdata;
pdata = NULL;
DelMap