我只是在寻找关于我正在研究的项目的一点指导......我有一般的想法,但似乎无法获得正确放置的代码。Java UDP服务器编程
目标如下: 编写一个UDP'CompressionServer',它将接收用户的输入,直到它看到一个“魔术字符串”,此时它将在文件系统中创建一个压缩和未压缩的文件版本。因此,我需要将以下“Zip”代码集成到我的UDP服务器代码中(它已经创建了未压缩的文件)......这就是我现在被卡住的地方。在我写入“fout”之后,我的第一批尝试有Zip代码,但未能创建ZIP文件。
我想这里的要点是我应该包括什么是邮政编码的关键部分,什么是将他们放在我的服务器代码中的最佳位置......任何帮助表示赞赏!
邮编:
import java.io.*;
import java.util.zip.*;
public class Zip {
static final int BUFFER = 2048;
public static void main (String argv[]) {
try {
String fileInput = argv[0];
String fileOutput = argv[1];
BufferedInputStream origin = null;
// Create a file output stream
FileOutputStream dest = new
FileOutputStream(fileOutput);
ZipOutputStream out = new ZipOutputStream(new
BufferedOutputStream(dest));
//out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
// get a list of files from current directory
FileInputStream fi = new
FileInputStream(fileInput);
origin = new
BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(fileInput);
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
服务器代码:
import java.net.*; // for DatagramSocket, DatagramPacket, and InetAddress
import java.io.*; // for IOException
public class CompressionServer {
private static final int ECHOMAX = 65535; // Maximum size of echo datagram
private static final int BUFFER = 2048;
public static void main(String[] args) throws IOException {
int servPort = Integer.parseInt(args[0]);
DatagramSocket socket = new DatagramSocket(servPort);
DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);
for (;;)/>/>/> { // Run forever, receiving and echoing datagrams
socket.receive(packet); // Receive packet from client
// Get data from packet
byte[] data = packet.getData();
// Create new string from bytes w/ offset -- contains name of file
String fileName = new String(data, 0, packet.getLength());
// Create file output stream w/ file name
FileOutputStream fout = new FileOutputStream(fileName.trim());
// Receive bytes from socket, write bytes to file & flush
while (true) {
// Receive
socket.receive(packet);
data = packet.getData();
String tmp = new String(data, 0, packet.getLength());
// Determine if need to break from loop
if (tmp.indexOf("--------MagicString") != -1) {
break;
}
// Write & Flush
fout.write(data, 0, packet.getLength());
fout.flush();
}
}
// Close
fout.close();
}
/* NOT REACHED */
}
}