需要建两个类,分别作为服务器(接收文件)和客户端(发送文件)
1.服务器类:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器-用来接收文件
*/
public class FileServer {
public static void main(String[] args) {
//自己的ip地址
String ip = InetAddress.getLoopbackAddress().getHostAddress();
int port = 33999;
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
Socket s = ss.accept();//接收从服务器传来的文件
// InputStream in;
//接收的文件以ip地址为名显示
String cip = s.getRemoteSocketAddress().toString().replace(".", "").replace(":", "") + ".jpg";
System.out.println(cip);
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
//输出显示接收到的文件
// File file;
try {
FileOutputStream fos = new FileOutputStream("D:/Users/Administrator/Desktop" + cip);
byte[] buf = new byte[1024];
int len = -1;
while ((len = bis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.客户端类:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 客户端-用来发送文件
*/
public class FileClient {
public static void main(String[] args) {
String server_ip = "Localhost";//地址是谁,就发给谁,此处设的是本机
int port = 33999;
try {
// ServerSocket ss = new ServerSocket(port);
Socket s = new Socket(server_ip, port);
OutputStream os = s.getOutputStream();
//向服务器发送文件
// File file;
FileInputStream fis = new FileInputStream("D:/JavaFiles/Train/bg_gray.jpg");//发送给服务器的文件地址
//
byte[] buf = new byte[1024];//每次以1kb传输
int len = -1;
while ((len = fis.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.运行时,若自己测试(自己给自己传.jpg图片),先运行服务器类,再运行客户端类,成功运行后图片就会显示在服务器类填写的文件路径中.