我是 C++ 新手。我了解面向对象的编程。
我按照教程将这个客户端/服务器代码放在一起。我现在想在客户端断开连接时向服务器添加一条消息。
我用vs11
服务器:
#include "main.h"
using namespace std;
void main ( )
{
long answer;
WSAData wsaData;
WORD DLLVERSION;
DLLVERSION = MAKEWORD(2,1);
answer = WSAStartup(DLLVERSION, &wsaData);
//WINSOCK LOADED
SOCKADDR_IN addr;
int addrlen = sizeof(addr);
SOCKET sListen;
SOCKET sConnect;
SOCKET* Connections;
static int ConCounter = 0;
Connections = (SOCKET*)calloc(64, sizeof(SOCKET));
sConnect = socket(AF_INET,SOCK_STREAM,NULL);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
sListen = socket(AF_INET,SOCK_STREAM,NULL);
bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
listen(sListen, SOMAXCONN);
for(;;)
{
cout << "Wating for connection..." <<endl;
if(sConnect = accept(sListen, (SOCKADDR*)&addr, &addrlen))
{
Connections[ConCounter] = sConnect;
cout << "Connection found " << ConCounter <<endl;
answer = send(Connections[ConCounter], "YourMessage", 12, NULL);
ConCounter++;
}
}
}
客户:
#include "main.h"
using namespace std;
void main ( )
{
string confirm;
char message[200];
string strmessage;
long answer;
WSAData wsaData;
WORD DLLVersion;
DLLVersion = MAKEWORD(2,1);
answer = WSAStartup(DLLVersion, &wsaData);
SOCKADDR_IN addr;
int addrlen = sizeof(addr);
SOCKET sConnect;
sConnect = socket(AF_INET, SOCK_STREAM,NULL);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
cout << "Do you want to connect to the Server? [Y/N]" <<endl;
cin >> confirm;
if(confirm == "N")
{
exit(1);
}
else
{
if(confirm == "Y")
{
connect(sConnect, (SOCKADDR*)&addr, sizeof(addr));
answer = recv(sConnect, message, sizeof(message), NULL);
strmessage = message;
cout << strmessage <<endl;
getchar();
}
}
getchar();
}