我有代码TCP服务器发送文件,我试图保存从客户端文件这个字节,但客户端冻结读取。程序不会给出任何异常,并且很难调试。
服务器代码:
private void byteSend(Result result) {
try {
BufferedOutputStream outToClient = new BufferedOutputStream(clientSocket.getOutputStream());
File file = new File(Service.getInstance().getServer().getShareDirectory() + "/" + result.getData().toString().replace("__", " "));
byte[] byteArray = new byte[(int) file.length()];
FileInputStream fis;
try {
fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(byteArray, 0, byteArray.length);
outToClient.write(byteArray, 0, byteArray.length);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
outToClient.flush();
outToClient.close();
clientSocket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
客户代码:
// create file input stream
InputStream is = clientSocket.getInputStream();
// create new data input stream
DataInputStream dis = new DataInputStream(is);
// available stream to be read
int length = dis.available();
// create buffer
byte[] buf = new byte[length];
// read the full data into the buffer
dis.readFully(buf);
// for each byte in the buffer
for (byte b:buf)
{
// convert byte to char
char c = (char)b;
// prints character
System.out.print(c);
}
break;
如何解决此问题?你能给我一些提示吗?