我正在尝试为客户端/服务器聊天程序编写服务器。唯一的问题是,一旦客户端断开连接,服务器就会开始向服务器发送他们的最后一条消息。即使他们重新连接,它也会不断发送垃圾邮件。我试过谷歌搜索,但找不到任何东西。这是服务器代码:
#include "MasterServer.h"
using namespace std;
SOCKADDR_IN Server;
int addrlen = sizeof(Server);
SOCKET sListen;
SOCKET Connect;
SOCKET* Connections;
int port = 444;
int ConCounter = 0;
char* Recv = new char[256];
int ServerThread(int ID)
{
ZeroMemory(Recv, sizeof(Recv));
for(;;)
{
if(recv(Connections[ID],Recv ,256 ,NULL))
{
cout << Recv << endl;
}
}
}
int InitWinSock()
{
int RetVal = 0;
WSAData wsa;
WORD Version = MAKEWORD(2,1);
RetVal = WSAStartup(Version, &wsa);
return RetVal;
}
int main()
{
int RetVal = 0;
RetVal = InitWinSock();
if(RetVal != 0)
{
cout << "WinSock Start Up Failure";
}
Connections = (SOCKET*)calloc(64, sizeof(SOCKET));
sListen = socket(AF_INET, SOCK_STREAM, NULL);
Connect = socket(AF_INET, SOCK_STREAM, NULL);
cout << "\t\t----====ModernBacon Server====----"<< endl;
cout << "What Port Would You Like To Run On [Default 444]: ";
cin >> port;
system("cls");
Server.sin_addr.s_addr = inet_addr("127.0.0.1");
Server.sin_family = AF_INET;
Server.sin_port = htons(port);
bind(sListen, (SOCKADDR*)&Server, sizeof(Server));
//Listening
listen(sListen, 64);
cout << "Listening For Connections IP:"<<inet_ntoa(Server.sin_addr);"Port:"<<port<<
endl;
for(;;)
{
if(Connect = accept(sListen, (SOCKADDR*)&Server, &addrlen))
{
Connections[ConCounter] = Connect;
char* ID = new char[64];
ZeroMemory(ID, sizeof(ID));
itoa(ConCounter, ID, 10);
send(Connections[ConCounter], ID, sizeof(ID),NULL);
ConCounter = ConCounter + 1;
CreateThread(NULL,NULL, (LPTHREAD_START_ROUTINE)
ServerThread, (LPVOID)(ConCounter -1), NULL, NULL);
cout << "\t\tClient Connected!\tID: " <<
ConCounter << endl;
}
}
return(0);
}
我不知道发生了什么...