/** * Sends datagram to the given address using the given socket. * * @param env JNIEnv interface. * @param obj object instance. * @param sd socket descriptor. * @param address remote address. * @param buffer data buffer. * @param bufferSize buffer size. * @return sent size. * @throws IOException */ static ssize_t SendDatagramToSocket( JNIEnv* env, jobject obj, int sd, const struct sockaddr_in* address, const char* buffer, size_t bufferSize) { // Send data buffer to the socket LogAddress(env, obj, "Sending to", address); ssize_t sentSize = sendto(sd, buffer, bufferSize, 0, (const sockaddr*) address, sizeof(struct sockaddr_in)); // If send is failed if (-1 == sentSize) { // Throw an exception with error number ThrowErrnoException(env, "java/io/IOException", errno); } else if (sentSize > 0) { LogMessage(env, obj, "Sent %d bytes: %s", sentSize, buffer); } return sentSize; }
/** * Blocks and waits for incoming client connections on the * given socket. * * @param env JNIEnv interface. * @param obj object instance. * @param sd socket descriptor. * @return client socket. * @throws IOException */ static int AcceptOnSocket( JNIEnv* env, jobject obj, int sd) { struct sockaddr_in address; socklen_t addressLength = sizeof(address); // Blocks and waits for an incoming client connection // and accepts it //LogMessage(env, obj, "Waiting for a client connection..."); int clientSocket = accept(sd, (struct sockaddr*) &address, &addressLength); // If client socket is not valid if (-1 == clientSocket) { // Throw an exception with error number ThrowErrnoException(env, "java/io/IOException", errno); } else { // Log address LogAddress(env, obj, "Client connection from ", &address); } return clientSocket; }
// receive datagram from udp socket static ssize_t ReceiveDatagramFromSocket( JNIEnv* env, jobject obj, int sd, struct sockaddr_in* address, char* buffer, size_t bufferSize) { socklen_t addressLength = sizeof(struct sockaddr_in); // Receive datagram from socket LogMessage(env, obj, "Receiving datagram from the socket..."); ssize_t recvSize = recvfrom(sd, buffer, bufferSize, 0, (struct sockaddr*) address, &addressLength); // If receive is failed if (-1 == recvSize) { // Throw an exception with error number ThrowErrnoException(env, "java/io/IOException", errno); } else { // Log address LogAddress(env, obj, "Received datagram from", address); // NULL terminate the buffer to make it a string buffer[recvSize] = 0; // If data is received if (recvSize > 0) { LogMessage(env, obj, "Received %d bytes: %s", recvSize, buffer); } } return recvSize; }