java socket发送文件_java socket发送文件

[java]代码库package bookPromotation;

import java.io.*;

import java.net.*;

public class Client {

/**

* @param args

*/

private static File f = null;

static FileInputStream fr = null;

static DataOutputStream dout = null;

private static Socket s = null;

public static void main(String[] args) throws IOException {

Client sc = new Client();

sc.connectSocketServer(8000);

sc.sendFile("0", "jpg");

sc.sendFile("1", "jpg");

sc.sendFile("2", "jpg");

fr.close();

dout.close();

}

/**

* 连接服务器端

*

* @param port

* 要连接的服务器SocketServer端口

*/

public void connectSocketServer(int port) {

try {

s = new Socket(InetAddress.getLocalHost(), port);

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

// 发送文件

public void sendFile(String name,String type) {

byte[] b = new byte[1024];

f = new File(name+"."+type);

try {

// 数据输出流

dout = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));

// 文件读入流

fr = new FileInputStream(f);

int n = fr.read(b);

while (n != -1) {

// 向网络中写入数据

dout.write(b, 0, n);

dout.flush();

// 再次读取n字节

n = fr.read(b);

}

// 关闭流

System.out.println("send file successfully");

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}//源代码片段来自云代码http://yuncode.net

694748ed64b9390909c0d88230893790.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值