ソケットに停止メッセージを効率的かつ迅速に送信したい。ソケットに停止メッセージを送信する
私はあるパソコンから別のパソコンにファイルを送信する方法があります。送信者のすべてのファイルが受信者の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]);
}
、私は、ファイルのサイズを意味すると仮定? – Sunshine
@Sunshine - 正確に。 – mah