写n个字节并读取n个字节:使用uint16_t发送要读取的字节数

时间:2017-01-15 15:32:06

标签: c sockets tcp stdint

我一直在使用这些readwrite函数(由@alk提供) 问题是我不知道如何正确发送uint16_t data_size; 这是我发送一般示例缓冲区的实际代码:

uint16_t data_size;
int retry_on_interrupt = 0;
char buffer[] = "Hello world!";
data_size = (uint16_t) sizeof(buffer);    

/* sending data_size */
writen(socket, data_size, 2, retry_on_interrupt);

/* sending buffer */
writen(socket, buffer, sizeof(buffer);  

这是我接收一般示例缓冲区的实际代码:

/* receiving data_size */
readn(socket, &data_size, 2);

/* receiving buffer */
readn(socket, buffer, data_size);

但这不起作用,我认为因为writen需要const char *,而我使用的是uint16_t ... 这些电话怎么办?感谢。

1 个答案:

答案 0 :(得分:1)

替换

if (-1 == writen(socket, &data_size, sizeof data_size, 1))
{
   perror("writen() failed writing size");
   exit(EXIT_FAILURE);
}

通过

writen(socket, buffer, sizeof(buffer);  

并替换此行

if (-1 == writen(socket, buffer, data_size, 1))
{
   perror("writen() failed writing pay-load");
   exit(EXIT_FAILURE);
}

通过

public class Item
{
    [Key]
    public long Id { get; set; }

    [MaxLength(100)]
    [Required]
    public string Name { get; set; }

    [MaxLength(1000)]
    public string Description { get; set; }

    [Required]
    public decimal Price { get; set; }

    public Currency Currency { get; set; }

    public bool Negotiable { get; set; }

    public virtual List<Photo> Photos { get; set; }
    public Category Category { get; set; }

    [Required]
    public byte CategoryId { get; set; }

    [Required]
    public string OwnerId { get; set; }

    public ApplicationUser Owner { get; set; }
}

您肯定也想在读取功能中添加错误检查!

此外,您还希望在向不同硬件平台发送/接收时解决可能的endianness (byte-order)问题。