我想从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);
}
结果我得到了我的号码,然后是“socket read String failed”消息。 如果我不做测试我也没有任何结果
char myString[20] = "";
recv( to_server_socket, &myString, sizeof( myString), 0 );
答案 0 :(得分:0)
麻烦在于以下行:
char myString[30] = "";
if( recv( to_server_socket, &myString, sizeof( myString), 0 ) != sizeof( myString ))
您确定从Java发送的字符串是30个字符。在上面一行中,您正在检查recv的返回值,以查看该值是否为30,这可能不是这种情况。
只需打印recv的返回值,看看它是否获得任何数据以及该数据中存在多少个字符。