|
小弟最近初学Socket编程,自己在windows mobile6.0上编了一个读取服务端时间的例子,不能成功;因为初学,其中肯定有很多错误,请大家指教。谢谢!
1.先创建两个菜单按钮;一个"server",一个"client";
2.这两个按钮的单击事件分别创建一个线程,线程的回调函数是ServerMain和ClientMain
3.先点击“server”按钮,启动server线程
4.在单击“client”按钮,启动client线程
问题:为什么没有读到服务器端事件??
代码如下:
“server”按钮事件:
void Server()
{
DWORD dwId;
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ServerMain, 0, 0, &dwId);
}
“client”按钮事件:
void Client()
{
DWORD dwId;
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ClientMain, 0, 0, &dwId);
}
static DWORD WINAPI ServerMain(LPVOID lpvParam)
{
int listenId,connId;
sockaddr_in serveraddr;
SYSTEMTIME time;
char buff[128];
listenId = socket(AF_INET, SOCK_STREAM, 0);
memset(&serveraddr, 0x00, sizeof(sockaddr_in));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(13);
bind(listenId, (sockaddr*)&serveraddr, sizeof(sockaddr));
listen(listenId, SOMAXCONN);
for( ; ;)
{
connId = accept(listenId, NULL, NULL);
GetSystemTime(&time);
sprintf(buff, "\n%04d年%02d月%02d日\n", time.wYear, time.wMonth, time.wDay);
send(listenId, buff, strlen(buff), 0);
}
return 0;
}
static DWORD WINAPI ClientMain(LPVOID lpvParam)
{
int sockfd;
char buff[128];
sockaddr_in servaddr;
socket(AF_INET, SOCK_STREAM, 0);
memset(&servaddr, 0, sizeof(sockaddr_in));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
connect(sockfd, (sockaddr*)&servaddr, sizeof(sockaddr));
while(recv(sockfd, buff, sizeof(buff), 0) > 0)
{
WCHAR wBuff[256];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, buff, -1, wBuff, sizeof(wBuff));
MessageBox(NULL, wBuff, L"Socket", 1);
}
return 0;
}
请高手赐教,为什么没有取到服务器段传过来的时间?谢谢:)
|
|