ソケット通信でファイル転送その2

簡単なファイル転送プログラムを作ってみた。

サーバ側のソースは以下。ソケットから受けとったバイト配列を、引数で指定したファイルのストリームに書き込んでいるだけ。特に理由はないが、32バイトずつその作業を行っている。

import java.net.*;
import java.io.*;
public class FileTranServer {
public static void main(String[] args) throws IOException{
if (args.length != 2)
throw new IllegalArgumentException("An argument should be port and filename");
int servPort = Integer.parseInt(args[0]);
String filename = args[1];
System.out.println("Output file name : " + args[1]);
//Create FileOutputStream
FileOutputStream fout = new FileOutputStream(filename);
//Create ServerSocket
ServerSocket servSock = new ServerSocket(servPort);
int recvMsgSize;
//int bufSize = servSock.getReceiveBufferSize();
int bufSize = 32;
System.out.println("Size of ReceiveBuffer : " + bufSize);
//Socket accepting loop
while(true){
System.out.println("Wait for accepting... ");
Socket clntSock = servSock.accept();
byte[] byteBuffer = new byte[bufSize];
System.out.println("Accepted client at " +
clntSock.getInetAddress().getHostAddress() +
" on port " +
clntSock.getPort());
//Create InputStream
InputStream in = clntSock.getInputStream();
//Read message and print it out
int totalByte = 0;
while((recvMsgSize = in.read(byteBuffer)) != -1){
System.out.println("Message : " + new String(byteBuffer,0,recvMsgSize));
System.out.println("Size    : " + recvMsgSize);
//Write to file
totalByte = totalByte + recvMsgSize;
fout.write(byteBuffer,0,recvMsgSize);
}
System.out.println("Recieved file size : " + totalByte);
clntSock.close();
fout.close();
fout = null;
}
}
}

次はクライアント側。これも引数で指定したファイルのストリームから、32バイトずつソケットのバイト配列に書き込むだけ。

import java.net.*;
import java.io.*;
public class FileTranClient {
public static void main(String[] args) throws IOException{
if (args.length != 3)
throw new IllegalArgumentException("Arguments should be host,port and filepath");
String server = args[0];
int serverPort = Integer.parseInt(args[1]);
String filename = args[2];
byte[] data = new byte[32];
//ソケットの作成
Socket socket = new Socket(server,serverPort);
System.out.println("Connected to server");
//ストリームの作成
FileInputStream fin = new FileInputStream(filename);
OutputStream out = socket.getOutputStream();
//ファイルの内容を読み出し、送信する
System.out.println("Sending file : " + filename);
int totalSize = 0;
int len = 0;
while ((len = fin.read(data)) != -1) {
totalSize = totalSize + len;
System.out.println(new String(data,0,len));
out.write(data, 0, len);
}
fin.close();
fin = null;
System.out.println("size of file : " + totalSize);
socket.close();
}
}

32バイトずつでも、250KBくらいだったらあっという間に送信できる。まあ同じPC内だから当たり前なのだろうか。別のPCと接続してやってみる必要あり。