I am unsure how to actually get this connection to write to client. In the function "server::write_data" I use "sendto" and it is here that I am being told "Socket is not connected". Having looked over the documentation and browsing example code I am a little baffled to be honest.
I am not experienced enough writing for OS X. It's a bit different from writing a socket in C/C++ for UNIX/Linux.
Can anyone (if you're savvy with OS X) please shed a little light on where I am going wrong?
I am calling "server->listen_incoming()" in main()
Many many thanks.
Server:
Code: Select all
server::server()
{
try
{
*** Do I use UDP???
_osx_sockfd = CFSocketCreate(kCFAllocatorDefault, AF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, server::handle_connect, NULL);
if (_listensock == -1)
{
throw socket_exception::create();
}
// clear the address structure
memset(&_serv_addr, 0, sizeof(_serv_addr));
_serv_addr.sin_family = AF_INET;
_serv_addr.sin_addr.s_addr = INADDR_ANY;
_serv_addr.sin_port = htons(LISTENING_PORT);
int reuse = 1;
if ((setsockopt(CFSocketGetNative(_osx_sockfd),
SOL_SOCKET,
SO_REUSEADDR,
(const char *)&reuse,
sizeof(reuse))) < 0)
{
perror("setting socket option");
exit(EXIT_FAILURE);
}
if (_osx_sockfd == NULL)
{
throw socket_exception::create_native();
}
CFDataRef sincfd = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&_serv_addr, sizeof(_serv_addr));
CFSocketError e = CFSocketSetAddress(_osx_sockfd, sincfd);
if (e != kCFSocketSuccess)
{
throw socket_exception::socket_set_address();
}
CFRelease(sincfd);
}
catch (const socket_exception::create & e)
{
exception_message(e);
}
catch (const socket_exception::bind & e)
{
exception_message(e);
}
}
void
server::handle_connect(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void * data, void * info)
{
std::cout << "connected" << std::endl;
}
void
server::write_data(const char * data)
{
try
{
memset(&_dest_addr, 0, sizeof(_dest_addr));
_dest_addr.sin_family = AF_INET;
_dest_addr.sin_addr.s_addr = inet_addr("192.168.0.2");
_dest_addr.sin_port = htons(LISTENING_PORT);
[b]ssize_t rc = sendto(CFSocketGetNative(_osx_sockfd), data, sizeof(data), 0, (const struct sockaddr*)&_dest_addr, sizeof(_dest_addr));[/b]
if (rc == -1)
{
perror("writing to socket failed");
}
}
catch (const socket_exception::write & e)
{
exception_message(e);
}
}
void
server::listen_incoming()
{
try
{
CFRunLoopSourceRef src = CFSocketCreateRunLoopSource(NULL, _osx_sockfd, 0);
if (src == NULL)
{
throw socket_exception::connect();
}
CFRunLoopAddSource(CFRunLoopGetMain(), src, kCFRunLoopDefaultMode);
std::cout << "waiting..." << std::endl;
}
catch (const socket_exception::listen & e)
{
exception_message(e);
}
catch (const socket_exception::accept & e)
{
exception_message(e);
}
}