DWORD ClientThread(LPVOID sock)
{
char recvbuf[1024];
sockcli *sockfd = (sockcli *)sock;
while(1)
{
int nRet = recv(sockfd->sockClient,recvbuf,sizeof(recvbuf),0);
if(nRet == -1)
{
printf("recv error!\n");
closesocket((SOCKET)sockfd->sockClient);
return 0;
}
else printf("Data recevied from %s is %s\n",inet_ntoa(sockfd->addr.sin_addr),recvbuf);
}
closesocket((SOCKET)sockfd->sockClient);
delete sockfd;
return 0;
}
int main(int argc, char* argv[])
{
SOCKET sockfd;
struct sockaddr_in serv_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)
{
struct sockaddr_in client_addr;
sockcli *pSockcli = new sockcli;
int len = sizeof(struct sockaddr);
pSockcli->sockClient = accept(sockfd,(struct sockaddr *)&client_addr,&len);
if(pSockcli->sockClient == -1)
{
perror("TCP socket accept error: ");
exit(0);
}
else printf("connection accepted on socket %d from %s\n",pSockcli->sockClient,inet_ntoa(client_addr.sin_addr));
pSockcli->addr =client_addr;
dwrecvClientThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&ClientThread,pSockcli,0,&ThreadAddr);
if(!dwrecvClientThread)
printf("can't create client thread!\n");
CloseHandle((HANDLE)dwrecvClientThread);
}
return 0;
}
tcp thread socket
------解决方案--------------------------------------------------------
两个客服端怎么建立TCP连接?
------解决方案--------------------------------------------------------
那你得需要把你想要发到的客服端信息告诉服务器对吧, 比如A B两个客服端连接服务器C的时候,C记录了A,B 名字 ID IP 之类的信息, A 要向 B发的时候,就告诉C 一个 名字,ID, IP 之类的信息,服务器再在本地找到目的端的地址,发过去就行了。
------解决方案--------------------------------------------------------
特供调试多线程程序使用:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
#include <windows.h>
#include <io.h>
#else
#include <unistd.h>