java - Cannot receive a String with socket -
i want send integer , string java server c client. can read integer have problem reading string. server code in java
clientnumber++; dataoutputstream dos = new dataoutputstream(socket.getoutputstream()); //dos.flush(); dos.writeint(clientnumber); string randomstring= getrandomvalue(10,20); dos.writeutf(randomstring);
this c client code:
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); }
as result got number , "socket read string failed" message. if don't test don't have result
char mystring[20] = ""; recv( to_server_socket, &mystring, sizeof( mystring), 0 );
the trouble below line:
char mystring[30] = ""; if( recv( to_server_socket, &mystring, sizeof( mystring), 0 ) != sizeof( mystring ))
are sure string sending java of 30 characters. in above line checking return value of recv see if value 30, may not case.
just print return value of recv , see if gets data , how many characters present in data.
Comments
Post a Comment