C socket读写

时间:2016-04-01 03:24:13

标签: c sockets

我对套接字服务器/客户端读/写感到困惑。我可以从客户端写到服务器,但我无法弄清楚如何从服务器写回客户端。客户端进入无限循环。这是我的代码。

服务器

sockdesc = socket(AF_INET, SOCK_STREAM, 0);
if ( sockdesc < 0 )
{
    cout << "Error creating socket" << endl;
    exit(0);
}
else{
    if ( getaddrinfo("0.0.0.0", portnum, NULL, &myinfo) != 0 )
    {
        cout << "Error getting address" << endl;
        exit(0);
    }
}
if (bind(sockdesc, myinfo->ai_addr, myinfo->ai_addrlen) < 0 ){
    cout << "Error binding to socket" << endl;
    exit(0);
}
if ( listen(sockdesc, 1) < 0 ){
    cout << "Error in listen" << endl;
    exit(0);
}
connection = accept(sockdesc, NULL, NULL);
if ( connection < 0 ){
    cout << "Error in accept" << endl;
    exit(1);
}   
read(connection, (char*)&myStruct, sizeof(myStruct));
//some code goes here
//I do not know if i need to use connection or sockdesc in write(). When
//write back to client
write(connection, (char*)&myStruct, sizeof(myStruct)); 

客户端

sockdesc = socket(AF_INET, SOCK_STREAM, 0);
if ( sockdesc < 0 ){
    cout << "Error opening socket" << endl;
    exit(0);
}
if ( getaddrinfo(hostname, portnum, NULL, &myinfo) != 0 ){
    cout << "Error getting address" << endl;
    exit(0);
}
connection = connect(sockdesc, myinfo->ai_addr, myinfo->ai_addrlen);
if ( connection < 0 ){
    cout << "Error in connect" << endl;
    exit(0);
}
write(sockdesc, (char*)&myStruct, sizeof(myStruct));
//some code goes here
//I do not know if i need to use connection or sockdesc in read()
read(sockdesc, (char*)&myStruct, sizeof(myStruct));

0 个答案:

没有答案