struct info
{
SOCKET sockClient;
struct sockaddr_in client_addr;
}sock;
struct info sockcli;
DWORD ClientThread(LPVOID sock)
{
char recvbuf[1024];
while(1)
{
int nRet = recv((SOCKET)((struct info *)sock)->sockClient,recvbuf,sizeof(recvbuf),0);
if(nRet == -1)
{
printf("recv error!\n");
// closesocket((SOCKET)sockinfo->sockClient);
return 0;
}
else printf("Data recevied from %s\n",recvbuf);
}
// closesocket((SOCKET)sockinfo->sockClient);
// delete sockinfo;
return 0;
}
int main(int argc, char* argv[])
{
SOCKET sockfd;
struct sockaddr_in serv_addr,client_addr;
HANDLE dwrecvClientThread;
DWORD ThreadAddr;
WSADATA wsaData;
WORD wVersionRequest = MAKEWORD(1,1);
if(WSAStartup(wVersionRequest,&wsaData))
{
printf("start socket failed!\n");
exit(0);
}
if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("TCP socket create error: ");
exit(0);
}
else printf("TCP socket create ok!\n");
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) == -1)
{
perror("TCP socket bind error: ");
exit(0);
}
else printf("TCP socket bind ok!\n");
if(listen(sockfd,5) == -1)
{
perror("TCP socket listen error: ");
exit(0);
}
else printf("TCP socket listen ok!\n");
while(1)
{
int len = sizeof(struct sockaddr);
sockcli.sockClient = accept(sockfd,(struct sockaddr *)&client_addr,&len);
if(sockcli.sockClient == -1)
{
perror("TCP socket accept error: ");
exit(0);
}
else printf("connection accepted on socket %d from %s\n",sockcli.sockClient,inet_ntoa(client_addr.sin_addr));
sockcli.client_addr = client_addr;
dwrecvClientThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&ClientThread,(void *)&sockcli,0,&ThreadAddr);
if(!dwrecvClientThread)
printf("can't create client thread!\n");
CloseHandle((HANDLE)dwrecvClientThread);
}
return 0;
}
socket 多线程
------解决方案--------------------------------------------------------
应该new出来 兄弟
char * recvbuf = new char[1024]
------解决方案--------------------------------------------------------
struct sockaddr_in client_addr;
换个位置
------解决方案--------------------------------------------------------