-1

我想将一个整数和一个字符串从 Java 服务器发送到 C 客户端。我可以读取整数,但读取字符串时遇到问题。这是我在java中的服务器代码

ClientNumber++;
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//dos.flush();
dos.writeInt(ClientNumber);

String randomString= getRandomValue(10,20);
dos.writeUTF(randomString);

这是 C 客户端代码:

int to_server_socket = -1;

void main ( void )
{

    char *server_name = SERVEURNAME;
    struct sockaddr_in serverSockAddr;
    struct hostent *serverHostEnt;
    long hostAddr;
    long status;
    char buffer[512];

    bzero(&serverSockAddr,sizeof(serverSockAddr));
    hostAddr = inet_addr(SERVEURNAME);
    if ( (long)hostAddr != (long)-1)
        bcopy(&hostAddr,&serverSockAddr.sin_addr,sizeof(hostAddr));
    else
    {
        serverHostEnt = gethostbyname(SERVEURNAME);
        if (serverHostEnt == NULL)
        {
            printf("gethost rate\n");
            exit(0);
        }
        bcopy(serverHostEnt->h_addr,&serverSockAddr.sin_addr,serverHostEnt->h_length);
    }
    serverSockAddr.sin_port = htons(8071);
    serverSockAddr.sin_family = AF_INET;

    /* creation de la socket */
    if ( (to_server_socket = socket(AF_INET,SOCK_STREAM,0)) < 0)
    {
        printf("creation socket client ratee\n");
        exit(0);
    }
    /* requete de connexion */
    if(connect( to_server_socket,
               (struct sockaddr *)&serverSockAddr,
               sizeof(serverSockAddr)) < 0 )
    {
        printf("demande de connection ratee\n");
        exit(0);
    }
    /* envoie de donne et reception */

    int value = htonl( 6 );
    int reply = 0;

    if( send( to_server_socket, &value, sizeof( value ), 0 ) != sizeof( value ) )
    {
        printf( "socket write failed");
        exit( -1 );
    }

    if( recv( to_server_socket, &reply, sizeof( reply ), MSG_WAITALL ) != sizeof( reply ) )
    {
        printf( "socket read failed");
        exit( -1 );
    }

    printf( "got reply: %d\n", ntohl( reply ) );

    char myString[30] = "";
    ssize_t nbytes=0;

    if ((nbytes = recv(to_server_socket, myString, sizeof(myString), 0 )) < 0)
    {
        perror("recv");
        exit(1);
    }
    myString[nbytes - 1] = '\0';


    printf("Recived String : %s",myString);


}

结果我得到了我的号码,然后是“套接字读取字符串失败”消息。如果我不做测试,我没有任何结果

char myString[20] = "";
    recv( to_server_socket, &myString, sizeof( myString), 0 );
4

1 回答 1

0

问题在于以下行:

 char myString[30] = "";

 if( recv( to_server_socket, &myString, sizeof( myString), 0 ) != sizeof( myString ))

您确定从 Java 发送的字符串是 30 个字符吗?在上面的行中,您正在检查 recv 的返回值以查看该值是否为 30,但情况可能并非如此。

只需打印 recv 的返回值并查看它是否获取任何数据以及该数据中存在多少个字符。

于 2013-05-04T12:12:12.157 回答