gpt4 book ai didi

java - 在套接字中发送停止消息

转载 作者:行者123 更新时间:2023-12-02 07:57:07 25 4
gpt4 key购买 nike

我想要一种有效且快速的方法在套接字中发送停止消息。

我有一种将文件从一台电脑发送到另一台电脑的方法。来自发送者的所有文件都会出现在接收者的 PC 上。然而,所有数据都被写入第一个文件(仅)。其他文件存在,但为空。发生这种情况是因为接收器方法不知道何时开始写入下一个文件。

发件人

public static void sendFile (final Socket sock, File source)
{
FileInputStream fileIn = null;

try
{
//Read bytes from the source file
fileIn = new FileInputStream(source);

//Write bytes to the receive
//No need to use a buffered class, we make our own buffer.
OutputStream netOut = sock.getOutputStream();

byte[] buffer = new byte[BUFFER_SIZE];
int read;

while ((read = fileIn.read(buffer)) != -1)
{
netOut.write(buffer, 0, read);
netOut.flush ();
}
//Send some stop message here
}
catch (Exception e)
{
e.printStackTrace ();
}
finally
{
if (fileIn != null)
{
try
{
fileIn.close ();
}
catch (IOException e)
{
e.printStackTrace ();
}
}
}
}

//Send files via socket
public static void sendFile (final Socket sock, File[] source)
{
for (int i = 0; i < source.length; i++)
sendFile (sock, source[i]);
}

接收者:

public static void receiveFile (final Socket sock, File destination)
{
BufferedOutputStream out = null;

try
{
//Receive data from socket
InputStream clientInputStream = sock.getInputStream();

//Write bytes to a file
out = new BufferedOutputStream (new FileOutputStream (destination));

byte[] buffer = new byte[BUFFER_SIZE];
int read;
while (true)
{
read = clientInputStream.read(buffer);


out.write(buffer, 0, read);
out.flush ();
}
}
catch (IOException e)
{
e.printStackTrace ();
}
finally
{
if (out != null)
{
try
{
out.close ();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}

//Receive files via socket
public static void receiveFile (final Socket sock, File[] destination)
{
for (int i = 0; i < destination.length; i++)
receiveFile (sock, destination[i]);
}

最佳答案

在发送文件之前,您需要修改发送/接收协议(protocol)以至少包含最小 header 。您的 header 应至少包含要遵循的数据的大小以及您可能需要的任何其他内容(例如文件名)。

关于java - 在套接字中发送停止消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474626/

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