在Java服务器中接收ios套接字数据

时间:2013-03-12 10:53:28

标签: java ios sockets

我必须实现一个从智能手机上运行的ios应用程序接收数据(字符串)的java服务器。

不幸的是,我从未在类似的情况下工作过,所以我想知道是否有人可以给我一些指示从哪里开始(或信息资源来研究)。

我这里有用于创建套接字并发送数据的ios代码:

-(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;
        }

    }
}

提前致谢

1 个答案:

答案 0 :(得分:0)

这可能是一个很好的起点:Java Network Programming FAQ。另外,请记住,当您通过网络进行通信时,字符串只是字符串。这不像你将以某种方式在java中获得NSString;)