libsocket
libsocket copied to clipboard
Getting basic UDP example working?
Hi, Not really an issue but I am a newbie c++ programmer trying to get a very basic UDP communication example working. I am running echo_server.cpp on 1 computer and echo_client_conn.cpp on another computer. I am getting
input: Error while reading! (Connection refused)
when I run the client program. The server program doesn't seem to be giving error. Can you help me diagnose what is the issue? I did not change anything besides the host value. Also ping to the server from client works. Thanks!
# include <iostream>
# include "../headers/inetserverdgram.hpp"
# include "../headers/exception.hpp"
# include <cstring>
// Server for echo_client_*.cpp
// simply receives a message and sends an answer.
int main(void)
{
using std::string;
string host = "192.168.0.111"; //ip address of server computer
string port = "1234";
string answer("Hello back from the server!");
string from;
string fromport;
string buf;
buf.resize(32);
try {
libsocket::inet_dgram_server srv(host,port,LIBSOCKET_BOTH);
for (;;)
{
srv.rcvfrom(buf,from,fromport);
std::cout << "Datagram from " << from << ":" << fromport << " " << buf << std::endl;
srv.sndto(answer,from,fromport);
}
srv.destroy();
} catch (const libsocket::socket_exception& exc)
{
std::cerr << exc.mesg;
}
return 0;
}
client code
# include <iostream>
# include <unistd.h>
# include "../headers/inetclientdgram.hpp"
# include "../headers/exception.hpp"
/*
* Sends and receives messages via connected UDP sockets
*/
int main(void)
{
using std::string;
string host = "192.168.0.111";//also put address of server here?
string port = "1234";
string answer;
answer.resize(32);
libsocket::inet_dgram_client sock(LIBSOCKET_IPv4);
try {
std::cout << sock.gethost();
} catch (const libsocket::socket_exception& exc)
{
std::cerr << exc.mesg;
}
try {
for ( int i = 0; i < 20; i++ )
{
sock.connect(host,port);
sock << "Hello, server";
sock >> answer;
std::cout << "Answer from server: " << answer << std::endl;
sock.deconnect();
}
} catch ( const libsocket::socket_exception& exc )
{
std::cerr << exc.mesg;
}
sock.destroy();
return 0;
}
Now I have the following error on my server side:
/home/pi/gitlibs/inetdgram.cpp:88: inet_dgram_rcvfrom() - recvfrom() failed -- could not receive data from peer! (Success!)
Client seems to be running on infinite loop still.
Do you have any firewall or network restrictions in place? Does it work when running server and client on the same machine?