Reputation: 13
I am trying to have 2 way communication running between C sockets. For having the sockets set up, I was following the instructions on this link (http://www.linuxhowtos.org/C_C++/socket.htm) and everything worked fine. Sending messages from the client to the server worked perfectly.
However, I would also like the ability of the server to send response messages back to the client. How is this accomplished? If I set up a client and server connection at both ends, one of them cannot bind.
edit more code. Currently, I've used this style of sockets and put them into c++ code, just because that's my familiarity. Ignore the object oriented-ness.
//main call
if (server)
{
Connection recv(true, "servername");
recv.GetMsg();
recv.SendMsg("test", 4);
}
else // client
{
Connection snd(false, "servername");
snd.GetMsg();
snd.SendMsg("this is a test", 14);
}
And inside the Connection class,
void SendMsg(char *msg, int msg_length)
{
send(some_socket, msg, msg_length, 0);
};
void GetMsg()
{
recvd = recv(opponent_socket, buffer, sizeof(buffer), 0);
buffer[recvd] = '\0';
cout << "Printing msg: " << buffer << endl;
};
Connection::Connection(bool isserver, char *servername)
{
is_server = isserver;
server = servername;
opponent_socket = 0;
some_socket = socket(PF_INET, SOCK_STREAM, 0);
if (some_socket < 0)
{
cout << "Connection failed.\n" << endl;
exit(-1);
}
if (is_server)
{
AddrSetupServer(); // standard calls here. Pretty well what's shown in link provided
BindServer();
ListenServer();
WaitConnectionServer();
}
else
{
AddrSetupClient();
ConnectClient();
}
};
Upvotes: 1
Views: 2950
Reputation: 61369
Once you have a connection, it is bidirectional; simply send your response over the socket.
Upvotes: 2