我正在尝试从客户端向服务器发送文件,然后服务器响应客户端。服务器已收到该文件,但客户端未收到响应。
这是我的主要和客户代码:
public static void main(String[] args) throws IOException {
startServer();
startSender();
}
public static void startSender() {
(new Thread() {
@Override
public void run() {
try {
Socket client = new Socket("localhost", 10000);
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
//sent a file
FileInputStream fis = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\constructor.jpg"));
byte[] buffer = new byte[1024];
int length = 0;
while((length = fis.read(buffer, 0, buffer.length)) > 0){
oos.write(buffer, 0, length);
oos.flush();
}
//response
String response = (String) ois.readObject();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}).start();
}
服务器:
public static void startServer() {
(new Thread() {
@Override
public void run() {
ServerSocket server = null;
Socket client = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
server = new ServerSocket(10000);
client = server.accept();
System.out.println("Connected!");
ois = new ObjectInputStream(client.getInputStream());
oos = new ObjectOutputStream(client.getOutputStream());
//receive the file
FileOutputStream fos = new FileOutputStream(new File("E:\\Java\\server\\constructor1.jpg"));
byte[] sendBytes = new byte[1024];
while(true) {
int read =0;
read = ois.read(sendBytes);
if(read == -1)
break;
fos.write(sendBytes, 0, read);
fos.flush();
}
//response
oos.writeObject("true");
oos.flush();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}).start();
}
怎么了?
答案 0 :(得分:-1)
您必须在ObjectInputStream之前创建ObjectOutputStream。见下文:
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
这应该可以解决你输出TEST的问题。
答案 1 :(得分:-1)
您的接收方正在读取流直到流结束,但发送方没有关闭套接字,因此流的结束永远不会发生。您需要以某种方式更改发送协议: