【发布时间】:2020-04-29 09:02:37
【问题描述】:
我在java中有一个客户端-服务器程序,客户端向服务器发送请求,服务器通过发送文件来响应。 与服务器的连接正确,客户端发送的第一个请求被服务器正确解释。
此时,服务器读取一个特定文件,该文件似乎读得很好,因为写入发送了正确的字节数和字符串(通过打印字节数和字符串的打印进行测试)。
发送第一条消息后,客户端等待接收文件,但一旦收到消息,读取返回-1,好像它已经读取了一个EOF,我无法理解原因,如何解决它?
发送文件时服务器上的方法
private void sendFile(Socket client, String path, DataOutputStream writer) {
File file = new File(path);
byte[] bytes = new byte[1024];
InputStream in = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count;
try {
while ((count = in.read(bytes)) > 0) {
System.out.println("nBytes " + count);
String tmp = new String(bytes);
System.out.println(tmp);
//i'm reading from a json file this string
//[{"username":"user"},{"score":0},{"friendList":["us1","us2"]},{"password":"password"}]
//and it is printed correctly
writer.write(bytes, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
客户端方法
public void getFile (String username) {
// first of all connects correctly with the server and sends a message, the message is received correctly by the server, after it waits for a reply message
Socket socket = connect2server();
DataInputStream reader = null;
BufferedWriter writer = null;
try {
reader = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//send message to the server using writer
OutputStream out = null;
String file = username+".json";
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] bytes = new byte[1024];
int count;
try {
while ((count = reader.read(bytes)) >= 0) {
System.out.println("nByte " + count);
out.write(bytes, 0, count);
}
// the client is waiting correctly on the read but as soon as it receives a message, the read returns -1 as if it had only read an EOF and not the whole message
System.out.println(count);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
out.close();
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
【问题讨论】:
标签: java file server client datainputstream