2

我正在使用 Java 套接字进行聊天实现。我专注于一些功能,比如身份验证、一个人聊天和群聊。我正在考虑添加文件传输功能,我想知道这有什么好的做法。我应该在服务器上有单独的套接字,不同的端口只监听文件传输吗?现在,我从服务器套接字获得的输入和输出流分别绑定到 Scanner 和 PrintWriter 对象,因此我发现很难将其用于文件传输。

非常感谢你们可以推荐或给我好的建议的任何模式。

谢谢,

泽口

4

2 回答 2

3

好吧,FTP 为每个文件传输创建一个新的套接字。请注意,可以在与用于聊天的端口相同的端口上建立连接,但使用不同的初始化对话框。

于 2010-04-21T07:32:23.807 回答
-1

如果您可以使用本机库来做到这一点,它会更快。除非有充分的理由,否则除非有充分的理由,否则无法使用可以解决所有问题的库。

如果你真的需要用纯 Java 发送文件。这是基于我的一个旧项目的一种方法。但是请注意,有一些序列化开销,但是其中大部分可以通过使用此处讨论的 NIO 等效项来消除,或者您可以稍微进一步并使用零复制,它可以让您告诉操作系统将文件直接复制到套接字而无需任何中间副本。这仅适用于文件,而不适用于其他数据。

您应该在单独的线程中执行此操作,以便在文件传输时聊天仍然有效。创建一个套接字并为其提供一些标准端口(您可以为其提供端口 0,它只选择下一个可用端口,但随后您需要将该信息发送给其他接收者,因此仅使用标准端口更容易)。然后将您的文件分成块并使用套接字传输它:

//Send file (Server)
//Put this in a thread
Socket socket = new Socket(destinationIP, destinationPort);
ObjectOutputStream sender = new ObjectOutputStream(socket.getOutputStream());
sender.writeObject(dataToSend);

//Receive File (Client)
//Kick off a new thread to receive the file to preserve the liveness of the program
ServerSocket serverSocket = new ServerSocket(ListenPort);
socket = new Socket();
while (true) {
        new Thread(new TCPReceiver(socket)).start();
}

//Receive file thread TCPReceiver(Socket socket)
//Get the stream where the object is to be sent
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

/*  Where type is the type of data you send... String or anything really...
    read part of the file into something and send it then at this end use the same data                                                       
    type to recieve it and it will magically pull the entire object across.
*/
while(fileIsIncomplete){
    type recievedData = (type) objectInputStream.readObject();
    //Reconstruct file
}

希望这足以让您快速启动并运行文件发送器:)

编辑:删除废话。添加了原生点和零复制提及。

于 2012-02-06T23:35:15.887 回答