デバッグ時にプログラムが機能し、通常の実行で失敗する理由がわかりません。
ソケット経由でファイルをフィードする単純なサーバーをセットアップしました。クライアントが接続すると、このタスクを実行するためにスレッドが開始されますが、失敗します。「ソケットが閉じられています」というエラーが表示されます。
これは宿題です。なぜこれが起こっているのかを理解するまで先に進むことはできません。正しい方向に少しずつ動かしてください。
デバッグで動作させるために、クライアント接続を受け入れるサーバー クラスにブレーク ポイントを設定しました。
前もって感謝します。
public class File_Server {
private static ServerSocket servsock;
public static void main(String[] args) throws IOException
{
// create socket
try {
servsock = new ServerSocket(4444);
} catch (Exception e) {
System.out.println("Port already in use.");
System.exit(1);
}
while (true) {
System.out.println("Waiting...");
try (Socket sock = servsock.accept()) {
System.out.println("Accepted connection : " + sock);
Thread t = new Thread(new CLIENTConnection(sock));
t.start();
} catch (Exception e) {
System.out.println("Cannot accept connection.");
}
}
}
}
public class CLIENTConnection implements Runnable {
private Socket client;
CLIENTConnection(Socket client) {
this.client = client;
}
@Override
public void run()
{
try {
FileInputStream fis = null;
// sendfile
File myFile = new File("studentData.txt");
byte[] mybytearray = new byte[(int) myFile.length()];
fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = client.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
fis.close();
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class File_Client {
private static long start = System.currentTimeMillis();
private static int bytesRead;
private static int current = 0;
public static void main(String[] args) throws IOException
{
int filesize = 60223861; // filesize temporary hardcoded
try (Socket sock = new Socket("127.0.0.1", 4444)) {
System.out.println("Connecting...");
// receive file
byte[] mybytearray = new byte[filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("studentData-received.txt");
try (BufferedOutputStream bos = new BufferedOutputStream(fos)) {
bytesRead = is.read();//.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length - current));
if (bytesRead >= 0) {
current += bytesRead;
}
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println("Time taken " + (end - start) + " milliseconds");
}
} catch (Exception e) {
System.out.println("Cannot connect to server.");
}
}
}