我目前正在使用 Java 套接字。我创建了一个服务器端代码和客户端代码来通过套接字传输文件。我已经成功地将文件从客户端传输到同一系统中的服务器,但是如果我尝试在不同平台上使用不同的系统,则它无法正常工作。服务器端和客户端代码如下。
服务器端代码
public class FileTransferTestServer extends Thread{
private final Socket socket;
public FileTransferTestServer(Socket socket) {
// TODO Auto-generated constructor stub
this.socket = socket;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ServerSocket serverSocket = new ServerSocket(5000);
Socket socket = serverSocket.accept();
System.out.println("Connection Established with "+socket.getInetAddress().getHostAddress());
new FileTransferTestServer(socket).start();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String buffer = null;
String fileName = null;
if((buffer = br.readLine()) != null){
fileName = buffer;
}
FileOutputStream fos = new FileOutputStream(fileName);
int res = IOUtils.copy(is, fos);
System.out.println("res : "+res);
is.close();
fos.flush();fos.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端代码
public class FileTransferClient {
public FileTransferClient() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Socket socket = new Socket("172.16.4.23",5000);
File file = new File("/Users/Guest/Desktop/DQM.txt");
OutputStream outputStream = socket.getOutputStream();
PrintWriter out = new PrintWriter(outputStream);
out.println("file-transfer");
out.flush();
out.println(""+file.getName());
out.flush();
FileInputStream fis = new FileInputStream(file);
int res = IOUtils.copy(fis, outputStream);
out.flush();
outputStream.flush();
outputStream.close();
fis.close();
System.out.println("res : "+res);
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如何使这个程序在系统之间传输文件
我尝试过使用 Windows (Server) & Mac OS X(Client) 和 Windows (Server) & LinuxMint(Client)
注意:1.我想发送文件名后跟文件内容。2.文件内容可以是任何形式(文本或二进制文件)