300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java 网络编程之传输文件(一)

java 网络编程之传输文件(一)

时间:2023-01-07 19:58:04

相关推荐

java 网络编程之传输文件(一)

需要建两个类,分别作为服务器(接收文件)和客户端(发送文件)

1.服务器类:

import java.io.*;import .InetAddress;import .ServerSocket;import .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 .ServerSocket;import .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图片),先运行服务器类,再运行客户端类,成功运行后图片就会显示在服务器类填写的文件路径中.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。