gpt4 book ai didi

java - 如何确保使用java.net传递的文件与传输前一样

转载 作者:行者123 更新时间:2023-12-01 14:19:53 24 4
gpt4 key购买 nike

我正在研究java.net并尝试传输som文件。这是发件人代码

public static final FilesGetter filesGetter = new FilesGetter();
public static Socket s;
public static File[] files;

public static void main(String args[]) throws Exception{
s = new Socket("localhost", 3128);

while (true){
try{
files = filesGetter.getFilesList("/etc/dlp/templates/");
Socket s = new Socket("localhost", 3128);
args[0] = args[0]+"\n"+s.getInetAddress().getHostAddress()
+":"+s.getLocalPort();
if (files != null){
for (int i = 0; i < files.length; i++){
InputStream is = new FileInputStream(files[i]);
byte[] message = IOUtils.toByteArray(is);
s.getOutputStream().write(message);

byte buf[] = new byte[64*1024];
int r = s.getInputStream().read(buf);
String data = new String(buf, 0, r);

System.out.println(data);
}
}
} catch(Exception e){
System.out.println("init error: "+e);
}
}
}

这是接收者代码:

public class Consumer extends Thread{

public static Socket s;
public String customerId;
int num;
public static final Filter filter = new Filter();
public MimeParser mimeParser = new MimeParser(true);

public Consumer(int num, final Socket s, final String customerId){
this.num = num;
this.s = s;
this.customerId = customerId;

setDaemon(true);
setPriority(NORM_PRIORITY);
start();
}

public static void receive(final String customerId){
try {
int i = 0;

ServerSocket server = new ServerSocket(3128, 0, InetAddress.getByName("localhost"));

System.out.println("server started");
while (true){
new Consumer(i, server.accept(), customerId);
i++;
}
} catch (Exception e){
e.printStackTrace();
}
}

public void run(){
try {
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();

byte buf[] = new byte[64*1024];
int r = is.read(buf);

if (r < 0)
return;
ByteArrayInputStream bais = new ByteArrayInputStream(buf, 0, r);
MessageInfo mi = mimeParser.parseMessages(bais);
filter.getMessageAcceptability(mi.getPlainText(), customerId);
s.close();
} catch (Exception e){
System.out.println("init error: " + e);
}
}
}

我不确定数据完整性,因为服务器端的数据处理并未完全成功,并且不知道是否需要查找处理代码中的错误(当我使用rabbitmq)或在客户端-服务器代码中。我也不知道必须选择什么缓冲区大小。

最佳答案

在发送端你可以发送任意数量的数据,64*1024就可以了,send方法会循环直到所有数据都发送完毕。但在接收方,read 可能会在整个文件被读取之前返回,您必须循环读取,直到另一端关闭套接字。

在这些情况下,最好提前发送一个整数,指示您要发送的数据量,接收器将循环直到读取那么多字节。

例如:

int ret=0;
int offset=0;
int BUFF_LEN=64*1024;
byte[] buffer = new byte[BUFF_LEN];
while ((ret = is.read(buffer, offset, BUFF_LEN - offset)) > 0)
{
offset+=ret;
// just in case the file is bigger that the buffer size
if (offset >= BUFF_LEN) break;
}

关于java - 如何确保使用java.net传递的文件与传输前一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17703323/

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