简体   繁体   中英

Receive ios socket data in Java server

I have to implement a java server that receives data (strings) from ios applications running on smartphones.

Unfortunately, I have never worked in similar scenarios, so I was wondering if someone can give me some pointers where to start from (or info-resources to look into).

I have here the ios code used to create the socket and send the data:

-(bool)createSocket {
    sock = 0;
    if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
        NSLog(@"Failed to create socket, error=%s", strerror(errno));
        return false;}
    else {
        return true;
        NSLog(@"Socket created");
    }
}

-(bool) send:(NSString*) msg ipAddress:(NSString*) ip port:(int) p
{
    struct sockaddr_in destination;
    unsigned int echolen;
    int broadcast = 1;

    if (socketCreated==false) {
        NSLog(@"Socket assente");
        return false;
    }
    else
    {
        /* Construct the server sockaddr_in structure */
        memset(&destination, 0, sizeof(destination));

        /* Clear struct */
        destination.sin_family = AF_INET;

        /* Internet/IP */
        destination.sin_addr.s_addr = inet_addr([ip UTF8String]);

        /* IP address */
        destination.sin_port = htons(p);

        /* server port */
        setsockopt(sock,
                   IPPROTO_IP,
                   IP_MULTICAST_IF,
                   &destination,
                   sizeof(destination));
        char *cmsg = [msg UTF8String];
        echolen = strlen(cmsg);

        // this call is what allows broadcast packets to be sent:
        if (setsockopt(sock,
                       SOL_SOCKET,
                       SO_BROADCAST,
                       &broadcast,
                       sizeof broadcast) == -1)
        {
            perror("setsockopt (SO_BROADCAST)");
            exit(1);
        }
        if (sendto(sock,
                   cmsg,
                   echolen,
                   0,
                   (struct sockaddr *) &destination,
                   sizeof(destination)) != echolen)
        {
            printf("Mismatch in number of sent bytes\n");
            return false;
        }
        else
        {
            NSLog([NSString stringWithFormat:@"-> Tx: %@",msg]);
            return true;
        }

    }
}

Thanks in advance

This might be a good place to start: Java Network Programming FAQ . Also, keep in mind that strings are just strings when you're communicating via the network. It's not like you're going to get an NSString in java somehow ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM