function SendData() {
try {
for (var i = 0; i < 20; i++) {
var myVal = 'test' + i;
ws.send(myVal);
}
} catch (ex) {
alert(ex.message);
}
};
服务器端(VC写的)
BOOL InitTcpSocket()
{
WORD wVersionRequested;//版本号
wVersionRequested = MAKEWORD(1,1);//1.1版本的套接字
WSADATA wsaData;
//初始化Winsock
int err;
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
AfxMessageBox("WSAStartup error");
if (LOBYTE(wsaData.wVersion) != 1 ||
HIBYTE(wsaData.wVersion) != 1)
AfxMessageBox("高低字节不为一");
//判断高低字节是不是1,如果不是1.1的版本则退出
ServerTcpSocket = socket(AF_INET, SOCK_STREAM, 0);
//Socket地址结构体的创建
SOCKADDR_IN seraddr;
int serport=1818;
memset(&seraddr,0,sizeof(seraddr));
seraddr.sin_family=AF_INET;
seraddr.sin_port=htons(serport);
seraddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
err=bind(ServerTcpSocket, (SOCKADDR*)&seraddr, sizeof(SOCKADDR));
if(err!=0)
{
AfxMessageBox((TCHAR*)"绑定失败");
exit(0);
return false;
}
err=listen(ServerTcpSocket,255);
if(err!=0)
{
AfxMessageBox((TCHAR*)"监听失败");
return false;
}
return true;
}
DWORD WINAPI EstablishTcpConnection(LPVOID lpParameter)
{
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
HANDLE hThread;
while(1)
{
SOCKET *sockConn=(SOCKET *)malloc(sizeof(SOCKET));
*sockConn=accept(ServerTcpSocket,(SOCKADDR*)&addrClient,&len);
char recvBuf[1024]={0};
recv(*sockConn,recvBuf,1024,0);
MainWindow->GetDlgItem(IDC_RECVBOX)->SetWindowTextA(CString(recvBuf));
if(CString(recvBuf).Find("Sec-WebSocket-Key:")!=-1)
{
char (*sendBuf)[1024]=(char (*)[1024])websocket_parity(recvBuf);
send(*sockConn,(char *)sendBuf,strlen((char *)sendBuf),0);
free(sendBuf);
hThread=CreateThread(NULL,0,RecvTcpMessage,(LPVOID)sockConn,0,NULL);
CloseHandle(hThread);
}
else
{
CString html="<body style='background:black;color:white;font-size:32px;font-family:微软雅黑;'onload=\"alert('这个端口是为websocket准备的哟~');\">websocket测试</body>";
send(*sockConn,html,html.GetLength(),0);
ActiveConnection=*sockConn;
closesocket(*sockConn);
free(sockConn);
}
}
return 0;
}
DWORD WINAPI RecvTcpMessage(LPVOID lpParameter)
{
char recvBuf[1024];
SOCKET sockConn=*(SOCKET *)lpParameter;
ActiveConnection=sockConn;
while(1)
{
memset(recvBuf,0,1024);
recv(sockConn,recvBuf,1024,0);
char (*result)[1024]=(char (*)[1024])AnalyticData(recvBuf,sizeof(recvBuf));
if(result)Purify((char*)result);
else
{
AfxMessageBox("收到空消息");
break;
}
CString show;
ConvertUtf8ToGBK(show,(char*)result);
MainWindow->GetDlgItem(IDC_RECVBOX)->SetWindowTextA(show);
free(result);
}
free(lpParameter);
return true;
}
用抓包软件确认客户端确实发送了20次,但服务端基本每次只能接收两三次数据,这是什么问题?
服务端改成非阻塞模式也是一样,江湖救急阿!!!