java客户端接收,从Java客户端接收数据(数据包含INT,短,字符串)

I was searching for hours to get an answer about my question, but didnt find anything. Maybe I get some help here.

What I'm trying to do:

A Java-Client sends a message to a C-Server. The message contains different types like integer, short and also a string (e.g. message = int: total_msg_length; short: operation; string: hello --> total_msg-length=4 (size of integer), operation = 2 (size of short), hello = 5 (each letter is 1 byte=5).

So, how can I receive the message in my server? The code below receives an Integer (works fine). Next step will be to receive a short and then a string (converted in US-ASCII).

int *msg;

int recv_size;

int final_msg;

if( (recv_size = recv(client_socket, &msg, sizeof(msg), 0 )) < 0 ){

error_exit("Fehler bei recv(message_len)");

}

final_msg = endian_swap(msg);

printf("Message: %d\n", final_msg);

return final_msg;

Is there a way to use a byte array instead of char buffer? Im thankful for every help. Please excuse my bad english, I'm from germany :-)

解决方案

You need to create a generic "read_n_bytes" function.

This you can use to read the message-size, the operation and the text, in three successive calls.

Those three calls you then wrap in a function to be called to read an entire message.

A generic reader might look like this:

/*

* Reads n bytes from sd into where p points to.

*

* returns 0 on succes or -1 on error.

*

* Note:

* The function's name is inspired by and dedicated to "W. Richard Stevens" (RIP).

*/

int readn(int sd, void * p, size_t n)

{

size_t bytes_to_read = n;

size_t bytes_read = 0;

while (bytes_to_read > bytes_read)

{

ssize_t result = read(sd, p + bytes_read, bytes_to_read);

if (-1 == result)

{

if ((EAGAIN == errno) || (EWOULDBLOCK == errno))

{

continue;

}

# ifdef DEBUG

{

int errno_save = errno;

perror("read() failed");

errno = errno_save;

}

# endif

break;

}

else if(0 == result)

{

# ifdef DEBUG

{

int errno_save = errno;

fprintf(stderr, "%s: Connection closed by peer.", __FUNCTION__);

errno = errno_save;

}

# endif

break;

}

bytes_to_read -= result;

bytes_read += result;

}

return (bytes_read < bytes_to_read) ?-1 :0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值