java发送文件到服务器端,将文件从C++客户端传输到Java服务器

本文探讨了一个C++客户端向Java服务器发送文件时遇到的问题:当文件大小小于预设的PACKET_SIZE时,服务器接收的字节数超过实际发送的字节数。文章提供了客户端和服务器端的代码示例,寻求解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我有一个需要将文件发送到C++服务器的C++客户端。我将文件拆分为PACKET_SIZE(= 1024)个字节的块,并通过TCP套接字发送它们。在服务器端,我最多可以将PACKET_SIZE字节读到缓冲区。当客户端发送小于PACKET_SIZE的文件时,服务器会收到比发送的更多字节。即使我将字节数限制为文件的大小,文件也不同。我知道这个问题与客户端无关,因为我已经用C++服务器测试了它,并且它的工作完美无瑕。将文件从C++客户端传输到Java服务器

谢谢。

服务器:

public void run() {

DataInputStream input = null;

PrintWriter output = null;

try {

input = new DataInputStream (_client.getInputStream());

}

catch (Exception e) {/* Error handling code */}

FileHeader fh = recvHeader(input);

size = fh._size;

filename = fh._name;

try {

output = new PrintWriter(_client.getOutputStream(), true);

}

catch (Exception e) {/* Error handling code */}

output.write(HEADER_ACK);

output.flush();

FileOutputStream file = null;

try {

file = new FileOutputStream(filename);

}

catch (FileNotFoundException fnfe) {/* Error handling code */}

int total_bytes_rcvd = 0, bytes_rcvd = 0, packets_rcvd = 0;

byte [] buf = new byte [PACKET_DATA_SIZE];

try {

int max = (size > PACKET_DATA_SIZE)? PACKET_DATA_SIZE: size;

bytes_rcvd = input.read(buf,0, max);

while (total_bytes_rcvd < size) {

if (-1 == bytes_rcvd) {...}

++packets_rcvd;

total_bytes_rcvd += bytes_rcvd;

file.write (buf,0, bytes_rcvd);

if (total_bytes_rcvd < size)

bytes_rcvd = input.read(buf);

}

file.close();

}

catch (Exception e) {/* Error handling code */}

}

客户:

char packet [PACKET_SIZE] ;

file.open (filename, ios::in | ios::binary);//fopen (file_path , "rb");

int max = 0;

if (file.is_open()) {

if (size > PACKET_SIZE)

max = PACKET_SIZE;

else

max = size;

file.read (packet , max);

}

else {...}

int sent_packets = 0;

while (sent_packets < (int) ceil (((float)size)/PACKET_SIZE)) {

_write=send(_sd , packet, max,0);

if (_write <0) {...}

else {

++sent_packets;

if (size > PACKET_SIZE* sent_packets) {

if (size - PACKET_SIZE* sent_packets >= PACKET_SIZE)

max = PACKET_SIZE;

else

max = size - PACKET_SIZE* sent_packets;

file.read (packet , max);

}

}

}

2010-01-13

dimid

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值