java socket上传_java网络编程–socket上传文件 | 学步园

直接代码不多说!

服务端:

package scoket.file.server;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.*;;

public class FileServer {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

try {

ServerSocket server = new ServerSocket(8888);

Socket socket = new Socket();

while(true){

socket = server.accept();

InputStream is = socket.getInputStream();

OutputStream os = socket.getOutputStream();

byte[] b = new byte[1024];

//1、得到文件名

int a = is.read(b);

String filename = new String(b, 0, a);

System.out.println("接受到的文件名为:"+filename);

String houzhui = filename.substring(filename.indexOf("."), filename.length());

String rand = String.valueOf((int) (Math.random() * 100000));

filename = rand+houzhui;

System.out.println("新生成的文件名为:"+filename);

FileOutputStream fos = new FileOutputStream("f:\\"+filename);

int length = 0;

while((length=is.read(b))!=-1){

//2、把socket输入流写到文件输出流中去

fos.write(b, 0, length);

}

//fos.flush();

fos.close();

os.flush();

os.close();

is.close();

socket.close();

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

客户端

package scoket.file.client;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import java.net.UnknownHostException;

public class FileCilent {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

try {

Socket client = new Socket("192.168.3.28", 8888);

InputStream is = client.getInputStream();

OutputStream os = client.getOutputStream();

String filepath="e:\\MyServer.java";

File file = new File(filepath);

String filename = file.getName();

System.out.println("send's file name:"+filename);

//1、发送文件名

os.write(filename.getBytes());

FileInputStream fis = new FileInputStream(file);

byte[] b = new byte[1024];

int length = 0;

while((length=fis.read(b))!=-1){

//2、把文件写入socket输出流

os.write(b, 0, length);

}

os.close();

fis.close();

is.close();

System.out.println("send over");

} catch (UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值