我正在研究 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 时效果很好)或在客户端-服务器代码中。我也不知道必须选择什么缓冲区大小。