在
https://www.binarytides.com/code-a-simple-socket-client-class-in-c/
是工作代码。必须实现构造函数并创建类的实例。然后调用
connect()
从这个实例cf
这个
static
没有必要。。。
班
:
/**
TCP Client class
*/
class tcp_client
{
private:
int sock;
std::string address;
int port;
struct sockaddr_in server;
public:
tcp_client();
bool conn(string, int);
bool send_data(string data);
string receive(int);
};
:
tcp_client::tcp_client()
{
sock = -1;
port = 0;
address = "";
}
:
/**
Connect to a host on a certain port number
*/
bool tcp_client::conn(string address , int port)
{
//create socket if it is not already created
if(sock == -1)
{
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
perror("Could not create socket");
}
cout<<"Socket created\n";
}
// [ ... ]
}
main.cpp
:
int main(int argc , char *argv[])
{
tcp_client c; // create instance
string host;
cout<<"Enter hostname : ";
cin>>host;
//connect to host
c.conn(host , 80); // invoke method
//[ ... ]
}
代码是来自的不完整副本