1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
CChatServer::CChatServer()
{
cout << "Starting up TCP Chat server\n";
m_bIsConnected = false;
WSADATA wsaData;
sockaddr_in local;
int wsaret=WSAStartup(0x101,&wsaData);
if(wsaret!=0)
{
return;
}
local.sin_family=AF_INET;
local.sin_addr.s_addr=INADDR_ANY;
local.sin_port=htons((u_short)8084);
m_SListenClient=socket(AF_INET,SOCK_STREAM,0);
if(m_SListenClient==INVALID_SOCKET)
{
return;
}
if(bind(m_SListenClient,(sockaddr*)&local,sizeof(local))!=0)
{
return;
}
if(listen(m_SListenClient,10)!=0)
{
return;
}
m_bIsConnected = true;
return;
}
CChatServer::~CChatServer()
{
closesocket(m_SListenClient);
WSACleanup();
}
void CChatServer::StartListenClient()
{
sockaddr_in from;
int fromlen=sizeof(from);
m_SClient=accept(m_SListenClient,
(struct sockaddr*)&from,&fromlen);
if(m_SClient != INVALID_SOCKET)
m_vClientList.push_back(m_SClient);
//AfxBeginThread(ServerRecThread,(void *)m_SClient);
}
int CChatServer::SendMessagePort(string sMessage)
{
int iStat = 0;
list<SOCKET>::iterator itl;
if(m_vClientList.size() == 0)
return 0;
for(itl = m_vClientList.begin();itl != m_vClientList.end();itl++)
{
iStat = send(*itl,sMessage.c_str(),sMessage.size()+1,0);
if(iStat == -1)
m_vClientList.remove(*itl);
}
if(iStat == -1)
return 1;
return 0;
}
int CChatServer::RecClient(SOCKET sRecSocket)
{
char temp[4096];
int iStat;
//cout <<inet_ntoa(from.sin_addr) <<":"<<temp<<"\r\n";
iStat = recv(sRecSocket,temp,4096,0);
if(iStat == -1)
{
m_vClientList.remove(sRecSocket);
return 1;
}
else
{
cout <<":"<<temp<<"\n";
//SendMessagePort(temp);
return 0;
}
return 0;
}
|