我不知道为什么我的程序在调试时会起作用而在正常执行中失败。
我已经设置了一个简单的服务器来通过套接字提供文件。当客户端连接时,启动一个线程来执行此任务,但它失败了。我收到'Socket is closed'错误。
这是作业: 我无法前进,直到我弄清楚为什么会发生这种情况,并且只是想在正确的方向上轻推一下。
要使它在调试中工作,我在服务器类中设置断点,它接受客户端连接。
提前致谢。
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.");
}
}
}
答案 0 :(得分:2)
您正在犯忽略read()结果的常见错误。它返回实际读取的字节数,或EOS处的-1。在Java中复制流的方法如下:
while ((count = in.read(buffer)) >= 0)
{
out.write(buffer, 0, count);
}
其中'count'是一个int。