|
代码如下:
- //成员变量
- CString m_strLastError;
- HANDLE m_hRecvThread;
- SOCKET m_hClientSocket;
- //OnInitDialg中
- WORD wVersionRequested;
- WSADATA wsaData;
- int err;
-
- wVersionRequested = MAKEWORD( 2, 2 );
-
- err = WSAStartup( wVersionRequested, &wsaData );
- if ( err != 0 )
- {
- m_strLastError.Format(_T("WSAStartup错误,错误原因:%d"),WSAGetLastError());
- AfxMessageBox(m_strLastError);
- return FALSE;
- }
-
- if ( LOBYTE( wsaData.wVersion ) != 2 ||
- HIBYTE( wsaData.wVersion ) != 2 ) {
- WSACleanup( );
- AfxMessageBox(m_strLastError);
- return FALSE;
- }
复制代码
初始化完毕后,点击按钮 启动GPRS和SOCKET
- void CTestSocketDlg::OnButton1()
- {
- if (!CERasDial(_T("gprs"),_T("*99***1#"),_T("*"),_T(""),_T(""),_T("")))
- {
- m_strLastError.Format(_T("当前信号弱,GPRS拨号失败"));
- AfxMessageBox(m_strLastError);;
- }else
- StartSocketService(1);
- }
- BOOL CTestSocketDlg::StartSocketService( UINT nSocketType)
- {
- m_hClientSocket = socket(AF_INET,SOCK_STREAM,0);
- if (m_hClientSocket == INVALID_SOCKET)
- {
- m_strLastError.Format(_T("创建连接socket发生错误,错误信息:%d"),WSAGetLastError());
-
- return FALSE;
- }
- m_hRecvThread = CreateThread(NULL,0,RecvThread,this,0,NULL);
- if (m_hRecvThread == NULL)
- {
- closesocket(m_hClientSocket);
- m_hClientSocket = NULL;
-
- m_strLastError.Format(_T("创建数据接收线程错误,错误原因:%d"),GetLastError());
- return FALSE;
- }
- return TRUE;
- }
复制代码
线程函数
- DWORD WINAPI CTestSocketDlg::RecvThread(LPVOID lpParameter)
- {
- TRACE(_T("接收数据线程启动 \n"));
- CTestSocketDlg *pClientSocket = (CTestSocketDlg *)lpParameter;
-
- sockaddr_in m_SAI;
- m_SAI.sin_addr.S_un.S_addr = inet_addr("57.95.26.32");
- m_SAI.sin_family = AF_INET;
- m_SAI.sin_port = htons(5080);
- TRACE(_T("SOCKET Handle:%d in Thread \n"),pClientSocket->m_hClientSocket);
- int nRet = connect(pClientSocket->m_hClientSocket,(sockaddr *)&m_SAI,sizeof(sockaddr));
- if (nRet == SOCKET_ERROR)
- {
-
- return -1;
-
- }
-
- return 0;
- }
复制代码
|
|