关于服务器转发和群发的问题
我想问问有关于SOCKET服务器转发和群发消息的问题,用的是TCP协议.
我有结构提链表把连上的客户端IP和端口号都存储下来,我应该怎么转发?下面是我服务端的部分代码,请高手指导下,非常感激啊..另外客户端需要改变不?
还有就是下面程序中我些的多线程是否有错?我自己感觉怪怪的
DWORD WINAPI AnswerThread(LPVOID lparam)
{
SOCKET ClientSocket=(SOCKET)(LPVOID)lparam;
int bytesRecv;
char sendbuf[32]="";
char recvbuf[32]="";
while(1)
{
bytesRecv=SOCKET_ERROR;
for(int i=0;i<(int)strlen(recvbuf);i++)
{
recvbuf[i]='\0';
}
while(bytesRecv==SOCKET_ERROR)
{
bytesRecv=recv(ClientSocket,recvbuf,32,0);
}
send(ClientSocket,recvbuf,strlen(recvbuf),0);
cout<<recvbuf<<endl;
}
return 0;
}
struct test //创建链表存放CLIENT的IP和端口号
{ SOCKET ID;
int clientIP;
int port;
test *next;
};
test *head;//指导向链表头的指针
void main()
{
HWND hWnd;
unsigned int wMsg;
WSADATA wsadata;
int error;
error=WSAStartup(MAKEWORD(1,1),&wsadata);
if (error!=0)
{ cout<<"WSAStartup failed!"<<endl;
return;
}
if (LOBYTE(wsadata.wVersion)!=1 || HIBYTE(wsadata.wVersion)!=1)
{WSACleanup( );
return;
}
SOCKET socketserver=socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN addrserver;
addrserver.sin_family=AF_INET;
addrserver.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrserver.sin_port=htons(6000);
bind(socketserver,(SOCKADDR*)&addrserver,sizeof(addrserver));
listen(socketserver,10);
SOCKADDR_IN addrclient;
WSAAsyncSelect(socketserver,hWnd, wMsg, FD_CONNECT);
SOCKET sockconn;
test *ls;
test *le;
ls=new test;
le=ls;
head=NULL;
while (1)
{
int len=sizeof(SOCKADDR);
SOCKET sockconn=accept(socketserver,(SOCKADDR*)&addrclient,&len);
ls->ID=sockconn;
ls->clientIP=addrclient.sin_addr.S_un.S_addr;
ls->port=addrclient.sin_port;
if(head=NULL)
{ head=ls;
}
else
{
le->next=ls;
}
le=ls;
ls=new test;
char sendbuf[100]="welcome";
send(sockconn,sendbuf,strlen(sendbuf)+1,0);
char recvbuf[100];
recv(sockconn,recvbuf,strlen(recvbuf)+1,0);
cout<<recvbuf<<endl;
send(sockconn,recvbuf,strlen(recvbuf)+1,0);
if (lEvent=FD_CLOSE)
{ char clientclose[20]="exit";
send(sockconn,sendbuf,strlen(sendbuf)+1,0);
}
}
HANDLE hThread;
DWORD dwThreadId;
hThread=CreateThread(NULL,0, AnswerThread,(LPVOID)sockconn,0,&dwThreadId);
if(hThread==NULL)
{
cout<<"CreatThread AnswerThread() failed."<<endl;
}
else
{
cout<<"CreateThread OK."<<endl;
}
}