【发布时间】:2020-11-16 23:05:24
【问题描述】:
我正在尝试通过当前从客户端到服务器的套接字发送文件。要写入的文件已创建,但当我打开它时,它是空的。另外,如果我在发送文件后向服务器发送一个字符串,我发送的内容会被写入应该接收的文本文件中。
我只测试文本文件。
为什么会这样?我该如何纠正?
jbutton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png","txt");
fc.addChoosableFileFilter(filter);
int result = fc.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = fc.getSelectedFile();
String path = selectedFile.getAbsolutePath();
try {
userText.setText("Sending File: " + selectedFile);
file = new FileInputStream(path);
byte b[] = new byte[30000];
file.read(b,0,b.length);
os = connection.getOutputStream();
os.write(b,0,b.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
else if(result == JFileChooser.CANCEL_OPTION){
System.out.println("No File Select");
}
}
//get stream to send and receive data
private void setupStreams() throws IOException{
output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
input = new ObjectInputStream(socket.getInputStream());
showMessage("\n Streams Are now Set up \n");
}
//during the chat conversation
private void whileChatting() throws IOException{
String message = "You are now connected ";
showMessage(message);
ableToType(true);
do {
try {
message = (String) input.readObject();
showMessage("\n" + message);
byte b[] = new byte[30000];
InputStream is = socket.getInputStream();
FileOutputStream fr = new FileOutputStream("C:\\Users\\Documents\\TestingFileClientToServer.txt");
is.read(b,0,b.length);
fr.write(b,0,b.length);
}catch(ClassNotFoundException classNotFoundException) {
showMessage("\n Error on input \n");
}
}while(!message.equals("CLIENT - END"));
}
【问题讨论】:
-
仅供参考,除非您想要与之通信的另一端已经设置了一个,否则真的没有充分的理由再使用原始套接字了。如果您要设置连接的两端,WebSockets/WebSocket API 确实是一个更好的选择。
标签: java file client-server serversocket