我正在尝试使用c ++创建一个简单的聊天程序。
我对编程很陌生,所以我边做边学。
我遇到了一个我无法解决的问题。我正在“ Client”类中创建一个套接字,并且我希望Client类具有一个称为_sock的属性,当我创建套接字时,我想将其保存在_sock变量中以及需要使用它的地方套接字,我只使用我的_sock变量。
想象一下,我有一个名为Client的类,它具有SOCKET _sock属性,并且在某个地方我创建了这样的套接字:
_sock = socket(AF_INET, SOCK_STREAM, 0);
然后我使用此_sock像这样连接到服务器:
connect(_sock, (sockaddr*)&hint, sizeof(hint));
我的问题是,当我这样做时,我的程序崩溃了,但是如果我这样做,它不会崩溃:
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
,然后像这样连接到服务器:
connect(sock, (sockaddr*)&hint, sizeof(hint));
然后它正在工作....
_sock是该类的SOCKET属性。
代码:
string ipAdress = "127.0.0.1"; // IP Adress of the server
int port = 54000; // Listening port # on the server
// Initialize Winsock
WSAData data;
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &data);
if (wsResult != 0)
{
cerr << "Can't start winsock, Err #" << wsResult << endl;
return;
}
// Create socket
_sock = socket(AF_INET, SOCK_STREAM, 0);
if (_sock == INVALID_SOCKET)
{
cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
WSACleanup();
return;
}
// Fill in a hint structure
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipAdress.c_str(), &hint.sin_addr);
// Connect to server
int connResult = connect(_sock, (sockaddr*)&hint, sizeof(hint));
if (connResult == SOCKET_ERROR)
{
cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
closesocket(_sock);
WSACleanup();
return;
}
当我这样做时,程序崩溃。但是,如果我喜欢它,它就可以工作...:
string ipAdress = "127.0.0.1"; // IP Adress of the server
int port = 54000; // Listening port # on the server
// Initialize Winsock
WSAData data;
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &data);
if (wsResult != 0)
{
cerr << "Can't start winsock, Err #" << wsResult << endl;
return;
}
// Create socket
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET)
{
cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
WSACleanup();
return;
}
// Fill in a hint structure
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipAdress.c_str(), &hint.sin_addr);
// Connect to server
int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));
if (connResult == SOCKET_ERROR)
{
cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
closesocket(sock);
WSACleanup();
return;
}