gpt4 book ai didi

java - 无法使用套接字接收字符串

转载 作者:行者123 更新时间:2023-11-30 19:48:53 25 4
gpt4 key购买 nike

我想将一个整数和一个字符串从 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 );

最佳答案

问题出在下面一行:

 char myString[30] = "";

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

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

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

关于java - 无法使用套接字接收字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com