|
楼主 |
发表于 2011-8-4 11:00:52
|
显示全部楼层
#pragma comment(lib, "ws2_32.lib")
// CMY_Sock_UartDlg 对话框
SOCKET g_stSock; //socket套接字
WORD wVersionRequested;
WSADATA wsaData;
int m_err;
FILE *g_Fp;
void ThreadFunc()
{
fprintf(g_Fp, "Create Thread Sucees.\n");
SOCKADDR_IN addrClient;// 连接上的客户端ip地址
int Len = sizeof(SOCKADDR);
char ClinetIPInfo[64];
char recvBuf[50];
memset(recvBuf, 0, sizeof(recvBuf));
memset(ClinetIPInfo, 0, sizeof(ClinetIPInfo));
SOCKET sockConn = accept(g_stSock, (SOCKADDR*)&addrClient, &Len);// 接受客户端连接,获取客户端的ip地址
//char sendBuf[50];
//sprintf(sendBuf, "Welcome %s to here!", inet_ntoa(addrClient.sin_addr));// 组合消息发送出去
//send(sockConn,sendBuf,strlen(sendBuf)+1,0);// 发送消息到客户端
PCSTR IPInfo = inet_ntop(AF_INET, &addrClient.sin_addr, ClinetIPInfo, sizeof(ClinetIPInfo));
int ClientPorts = addrClient.sin_port;//获取客户端的端口号
fprintf(g_Fp, "==================================================== \n");
fprintf(g_Fp, "Client Info: \n");
fprintf(g_Fp, " 1.Client IP Address : %s \n", IPInfo);
fprintf(g_Fp, " 2.Client Ports : %s \n", ClientPorts);
fprintf(g_Fp, "==================================================== \n");
recv(sockConn, recvBuf, strlen(recvBuf), 0);// 接受客户端消息
fprintf(g_Fp, "Recv Client Message {%s}.\n", recvBuf);
}
// TODO: 在此添加额外的初始化代码
g_Fp = fopen("ContaolLogs.log", "a");
if (g_Fp < 0)
{
return FALSE;
}
fprintf(g_Fp, "Open Logs File Suceed.\n");
// 隐藏窗口
ModifyStyleEx(WS_EX_APPWINDOW, WS_EX_TOOLWINDOW);
WINDOWPLACEMENT wp;
wp.length = sizeof(WINDOWPLACEMENT);
wp.flags = WPF_RESTORETOMAXIMIZED;
wp.showCmd = SW_HIDE;
SetWindowPlacement(&wp);
//fprintf(g_Fp, "Conceal Windows Suceed.");
wVersionRequested = MAKEWORD( 2, 0 );
m_err = WSAStartup( wVersionRequested, &wsaData );
if ( 0 != m_err ) //检查Socket初始化是否成功
{
fprintf(g_Fp, "Socket2.0 Init Fail An Exit!\n");
fclose(g_Fp);
return FALSE;
}
//fprintf(g_Fp, "Socket2.0 Init Suceed .");
//检查Socket库的版本是否为2.0
if (LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 0 )
{
WSACleanup();
fprintf(g_Fp, "Check up Socket Version lib Fail!\n");
fclose(g_Fp);
return FALSE;
}
//2.创建socket,
g_stSock = socket( AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == g_stSock)
{
fprintf(g_Fp, "Socket Create Fail An Exit!\n");
fclose(g_Fp);
return FALSE;
}
SOCKADDR_IN addrSrv;
//SOCKADDR_IN addrClient;// 连接上的客户端ip地址
int BindRet = 0;
unsigned int SockPorts = 6000;
//int len=sizeof(SOCKADDR);
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(SockPorts);
BindRet = bind(g_stSock, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));// 绑定端口
if (BindRet != 0)
{
fprintf(g_Fp, "Bind Socket Prots(%d) Fail An Exit!\n", SockPorts);
fclose(g_Fp);
return FALSE;
}
listen(g_stSock, 5);
fprintf(g_Fp, "Socket Create Suceed!\n");
HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadFunc, NULL, 0, NULL); |
|