void CMyDlg::ConnectFunction()< xmlnamespace prefix ="o" ns ="urn:schemas-microsoft-com:office:office" />

{

SOCKET mySocket; //通訊端
WORD wVersionRequested; //版本號
WSADATA wsaData; //socket資料
int err;



wVersionRequested = MAKEWORD( 2, 2 ); //申請版本號


WSAStartup( wVersionRequested, &wsaData ); //開始監聽


try

{

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 ) {

SHowExpressMsg("找不到WinsocketDLL檔\n");

return ;

}



if ( LOBYTE( wsaData.wVersion ) != 2 ||

HIBYTE( wsaData.wVersion ) != 2 )

{

SHowExpressMsg("Couldn't find the right version for WinSock 2.2\n");

WSACleanup( );

return ;

}



SOCKADDR_IN ServerAddr; //伺服器位址
//創建一個socket ,參數為網際協定 流式 TCP

mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

ServerAddr.sin_family = AF_INET; //設置位址家族
ServerAddr.sin_port = htons(8888); //綁定埠
ServerAddr.sin_addr.s_addr = inet_addr("169.254.37.33"); //設置IP位址


//連接伺服器
if (connect(mySocket, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr)))

{

int error_code = WSAGetLastError();

SHowExpressMsg("連接伺服器失敗!");

SHowExpressMsg("Error connecting socket: \n");

return ;

}



InitialsendStruct(1);



SendDataStruct(mySocket);

// RectDataFromServer(mySocket);



closesocket(mySocket);

WSACleanup( );

}

catch( double )

{

SHowExpressMsg("意外的異常!\n");

}//try -- catch

}



//初始化要發送的資料
void CMyDlg::InitialsendStruct(int type)

{

switch(type)

{

case 1:

{

memset(&sendStruct,0x00,sizeof(sendStruct));

sendStruct=new MyStruct;

memcpy(sendStruct->mycmd,"01\0",3);

memcpy(sendStruct->paraStuNumorIp,"12345678910\0",64);

memcpy(sendStruct->paraPCNum_or_Mac,"daniu\0",64);

break;

}

case 2:

{

break;

}

}

}



void CMyDlg::SendDataStruct(SOCKET& mySocket)

{

//發送
send(mySocket,(char*)(&*sendStruct),sizeof(MyStruct),Null);



}



void CMyDlg::RectDataFromServer(SOCKET& mySocket)

{

memset(&sendStruct,0x00,sizeof(MyStruct));

//接受
recv(mySocket,(char*)(&*sendStruct),sizeof(MyStruct),Null);

}



//異常處理函數,顯示基本的錯誤資訊
void CMyDlg::SHowExpressMsg(CString msg)

{

MessageBox(_T(msg),_T("提示"),MB_OK);

}
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()