I have this class constructor in C++ :
SocketServer::SocketServer(int port)
{
this->port=port;
WSAStartup(MAKEWORD(2,0), &WSAData);
server = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
bind(server, (SOCKADDR *)&addr, sizeof(addr));
}
The client application with port no. 5555 can't connect to the server program on the another pc within the LAN network. I have tried different port no. too. How to resolve this? The error message is :
Error while connecting
: This is client.cpp :
#include <iostream>
#include <fstream>
#include "SocketClient.h"
using namespace std;
void onError(errorStruct *e)
{
cout << e->message << endl;
}
int main()
{
int port;
cout<<"Enter a port : ";
cin>>port;
SocketClient client("127.0.0.1", port);
client.setErrorCallback(onError);
client.connect();
string str;
while(1)
{
cout << ">";
getline(cin, str);
client.send(str);
}
client.close();
}
Edit 2 : SocketClient
SocketClient::SocketClient(std::string ip, int port)
{
this->ip=ip;
this->port=port;
this->connected=false;
initParameters();
initSocket(ip, port);
}
void SocketClient::initSocket(std::string ip, int port)
{
WSAStartup(MAKEWORD(2,0), &WSAData);
this->socket = WINSOCK_API_LINKAGE::socket(AF_INET, SOCK_STREAM, 0);
this->addr.sin_addr.s_addr = inet_addr(ip.c_str());
this->addr.sin_family = AF_INET;
this->addr.sin_port = htons(port);
}
void SocketClient::initParameters()
{
this->bytes_for_package_size=16;
this->size_of_packages=2048;
this->callback=NULL;
this->callbackError=NULL;
this->thread_started=false;
this->errorWhileReceiving=false;
this->errorWhileSending=false;
}
I guess your system works fine if the Server and Client are both on the same machine?
In your client code you have the line
SocketClient client("127.0.0.1", port);
You haven't given the code for SocketClient
, but I guess that this is the address and port of the server? If so, then your problem is that you need to give the IP address of the server: 127.0.0.1
is localhost
, or this computer.