void CServerDlg::ConnectServer()//跟客户端连接,为之后接收消息做准备
{
// TODO: 在此添加控件通知处理程序代码
//1.初始化网络套接字库。勾选了,已经初始化了。
//2.创建套接字
s = socket(AF_INET, SOCK_STREAM, 0);
//3.处理地址---网络字节顺序
addr.sin_family = AF_INET;
addr.sin_port = htons(10001);
addr.sin_addr.S_un.S_addr = INADDR_ANY;
//4.绑定端口和ip
bind(s, (sockaddr *)&addr, sizeof(addr));
listen(s, 5);
//设置套接字为异步套接
WSAAsyncSelect(s, this->m_hWnd, WM_SOCKET, FD_ACCEPT | FD_READ);
}
afx_msg LRESULT CServerDlg::OnSocket(WPARAM wParam, LPARAM lparam)
{
//异步套接字处理
static int count = 0;
CString str;
char cs[1024];
memset(cs, 0, sizeof(cs)); // 清空字符数组,以便在接收数据之前进行初始化
switch (lparam)
{
case FD_ACCEPT:
{
int length = sizeof(addr1);
//接收客户端的请求
s1 = accept(s, (sockaddr*)&addr1, &length);//accept函数接受客户端的连接请求
}
break;
case FD_READ:
{
count++;
int bytesReceived = recv(s1, cs, 1024, 0);
if (count == 1)
{
char* result = (char*)malloc(1024);
memset(result, 0, 1024);
string str = cs;
int start = str.find("Key: ");
str = str.substr(start + 5, 24);
str += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
string Websocket_key = str;
SHA1Context sha;
char inputstr[1024];
char* Message_Hex;
int i;
memset(inputstr, 0, sizeof(inputstr));
memcpy(inputstr, Websocket_key.c_str(), Websocket_key.length() + 1);//明文
SHA1Reset(&sha);
SHA1Input(&sha, inputstr, strlen(inputstr));
i = SHA1Result(&sha);
char Message_Digest[1024];
for (i = 0; i < 1024; i++) {
Message_Digest[i] = (uint8_t)((sha.Message_Digest[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
}
Websocket_key = base64_encode(reinterpret_cast<const unsigned char*>(Message_Digest), 20);
CString accept = "HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: " + CString(Websocket_key.c_str()) + "\r\n\r\n";
send(s1, accept.GetBuffer(1), accept.GetLength(), 0) != SOCKET_ERROR;
}
else {
(LPTSTR)cs;
string csAsString(cs);
int result = wsDecodeFrame(csAsString, out);
ActiveConnection = s1;
getPenWidth(CString(out.c_str()));
//GetDlgItem(IDC_LIST2)->SetWindowText(CString(out.c_str()));
if (out == "{\"typeName\":\"UgeeStartSign\",\"message\":{\"penwidth\":\"%s\"}}", m_penwidth)
{
ShowWindow(SW_SHOW);
m_MaxP = m_penwidth;
Opendevice();
}
if (out == "{\"typeName\":\"UgeeCloseSign\"}")
{
CRect rect;
GetClientRect(&rect);
int width = rect.Width();
int height = rect.Height();
SaveSignToBase64(width,height);
//string Base64;
//wsEncodeFrame(strRet.GetString(),Base64, WS_TEXT_FRAME);
string str = "{\"typeName\":\"UgeeSignBase64\",\"message\":\"" + strRet + "\"}";
PackData(ActiveConnection, str.c_str());
ShowWindow(SW_HIDE);
Closedevice();
/* send(s1, CString(responseMsg.c_str()).GetBuffer(1), CString(responseMsg.c_str()).GetLength(), 0) != SOCKET_ERROR;*/
//PostQuitMessage(0);
}
}
}
break;
}
return 0;
}
这里需要两个一个是SHA1,跟BASE64编码用来解码跟编码
MFCwebsocket实践
最新推荐文章于 2024-06-21 18:09:44 发布