vc++ 多线程编程 SOCKET通信
#include"StdAfx.h"#include<stdio.h>//服务器端程序DWORDWINAPIAnswerThread(LPVOIDlparam){SOCK...
#include "StdAfx.h"
#include <stdio.h>
//服务器端程序
DWORD WINAPI AnswerThread(LPVOID lparam)
{
SOCKET ClientSocket=(SOCKET)(LPVOID)lparam;
char szText[]="您好!\r\n";
int send_num=::send(ClientSocket,szText,strlen(szText),0);
::closesocket(ClientSocket);
return 0;
}
int main()
{
WSADATA wsaData;
int iRet=WSAStartup(MAKEWORD(1,1),&wsaData);
SOCKET m_socket;
m_socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(m_socket==INVALID_SOCKET)
{
WSACleanup();
return 0;
}
sockaddr_in service;
service.sin_family=AF_INET;
service.sin_addr.s_addr=inet_addr("172.16.3.250");
service.sin_port=htons(2501);
if(bind(m_socket,(SOCKADDR*)&service,sizeof(service))==SOCKET_ERROR)
{
closesocket(m_socket);
return 0;
}
else
printf("bind OK.\n");
if(listen(m_socket,20)==SOCKET_ERROR)
printf("Error listening on socket.\n");
else
printf("listening ok.\n");
SOCKET AcceptSocket;
printf("Waiting for a client to connect...\n");
while(1)
{
AcceptSocket=SOCKET_ERROR;
while(AcceptSocket==SOCKET_ERROR)
{
AcceptSocket=accept(m_socket,NULL,NULL);
}
printf("Client Connected.\n");
DWORD dwThreadId;
HANDLE hThread;
hThread=CreateThread(NULL,NULL,AnswerThread,
(LPVOID)AcceptSocket,0,&dwThreadId);
closehandle(hThread);
//Sleep(4000);
closesocket(AcceptSocket);
}
closesocket(m_socket);
return 0;
}
该服务器端程序为什么如果有注释掉的Sleep(4000)客户端就接收返回正确的数据,注释掉后就接受到0个字符?? 展开
#include <stdio.h>
//服务器端程序
DWORD WINAPI AnswerThread(LPVOID lparam)
{
SOCKET ClientSocket=(SOCKET)(LPVOID)lparam;
char szText[]="您好!\r\n";
int send_num=::send(ClientSocket,szText,strlen(szText),0);
::closesocket(ClientSocket);
return 0;
}
int main()
{
WSADATA wsaData;
int iRet=WSAStartup(MAKEWORD(1,1),&wsaData);
SOCKET m_socket;
m_socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(m_socket==INVALID_SOCKET)
{
WSACleanup();
return 0;
}
sockaddr_in service;
service.sin_family=AF_INET;
service.sin_addr.s_addr=inet_addr("172.16.3.250");
service.sin_port=htons(2501);
if(bind(m_socket,(SOCKADDR*)&service,sizeof(service))==SOCKET_ERROR)
{
closesocket(m_socket);
return 0;
}
else
printf("bind OK.\n");
if(listen(m_socket,20)==SOCKET_ERROR)
printf("Error listening on socket.\n");
else
printf("listening ok.\n");
SOCKET AcceptSocket;
printf("Waiting for a client to connect...\n");
while(1)
{
AcceptSocket=SOCKET_ERROR;
while(AcceptSocket==SOCKET_ERROR)
{
AcceptSocket=accept(m_socket,NULL,NULL);
}
printf("Client Connected.\n");
DWORD dwThreadId;
HANDLE hThread;
hThread=CreateThread(NULL,NULL,AnswerThread,
(LPVOID)AcceptSocket,0,&dwThreadId);
closehandle(hThread);
//Sleep(4000);
closesocket(AcceptSocket);
}
closesocket(m_socket);
return 0;
}
该服务器端程序为什么如果有注释掉的Sleep(4000)客户端就接收返回正确的数据,注释掉后就接受到0个字符?? 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询