网络编程中文件的上传和下载简单例子:
1. 文件的下载
//客户端
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
//端口号
Socket socket = new Socket("127.0.0.1", 4567);
try (InputStream is = socket.getInputStream();
// 获取服务器端文件输出到硬盘
//随机数获取文件名,防止重复
OutputStream os = new FileOutputStream(UUID.randomUUID().toString().subSequence(0, 7) + ".文件扩展名");) {
int len = 0;
byte[] b = new byte[1024 * 3];
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
System.out.println("下载完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//服务器端
public class Sever {
public static void main(String[] args) throws IOException {
//端口号保持一致
ServerSocket ss = new ServerSocket(4567);
// 获得客户端的socket
Socket s = ss.accept();
// 获得客户端的输出流
try (OutputStream os = s.getOutputStream(); InputStream is = new FileInputStream("文件名");) {
int len = 0;
byte[] b = new byte[1024 * 3];
while ((len = is.read(b)) > 0) {
os.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. 文件的上传
//客户端
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 6666);
try(InputStream is = new FileInputStream("a.wma");
OutputStream os = socket.getOutputStream())
{
int len = 0;
byte[] b = new byte[1024];
while((len=is.read(b)) != -1) {
os.write(b,0,len);
}
socket.shutdownOutput();
//接收服务器端是否上传完毕的信息
InputStream is2 = socket.getInputStream();
DataInputStream dis = new DataInputStream(is2);
System.out.println(dis.readUTF());
} catch (Exception e) {
e.printStackTrace();
}
socket.close();
}
}
//服务器端
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(6666);
Socket socket = server.accept();
try (InputStream is = socket.getInputStream();
OutputStream os = new FileOutputStream(UUID.randomUUID().toString().substring(0, 8) + ".wma");
OutputStream os2 = socket.getOutputStream();) {
int len = 0;
byte[] b = new byte[1024];
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
// 告诉客户端上传完毕
DataOutputStream dos = new DataOutputStream(os2);
dos.writeUTF("上传好了");
dos.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. 在网页显示:
public class NetServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8866);
while(true) {
System.out.println("与客户端建立连接,准备响应");
Socket socket = ss.accept();
try ( OutputStream os = socket.getOutputStream();)
{
//展示文本
String str = "hello,我是火星人,我来自地球...";
byte[] b = str.getBytes();
//设置响应头
String head = "HTTP/1.1 200 OK\r\n Content-Type text/html; charset=utf-8\r\n"
+ " Content-Length:" + b.length +"\r\n\r\n";
//将内容写出
os.write(head.getBytes());
os.write(str.getBytes());
System.out.println("响应到页面");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
运行结果:
注意浏览器地址与端口号一致
另外,网络编程要与多线程联合使用,但是我目前还不熟练