socket的简单运用01---上传下载文件

pc机的远程主机程序

send.java

import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
* filename : send.java
* company : **** Limited (android) 2012-2015
* compiler : eclipse 3.7.1
* remark : TODO
* created : 2012-3-5 weeds
* changed : 后来者居下
*/

/**
* filename : TODO
*/
public class send {

/**
*
@param args
*/
static File fname;
static int port=8888;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
readFile("d.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void SendFile(String fileName)
{
fname=new File(fileName);
try {
fname.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public static void readFile(String fileName) throws IOException
{
Socket cs=null;
try{
System.out.println("正在等待连接...");
ServerSocket ss=new ServerSocket(port);
while(true){
String filePath="D:\\yc.rar";
File fi=new File(filePath);
System.out.println("文件长度是:"+(int)fi.length());
cs=ss.accept();
System.out.println("建立socket链接");
DataInputStream dis=new DataInputStream(new BufferedInputStream(cs.getInputStream()));
dis.readByte();
DataInputStream fdata=new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps=new DataOutputStream(cs.getOutputStream());
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long)fi.length());
ps.flush();
byte[] b=new byte[102400];
while(true){
int read=0;
if(fdata!=null){
read=fdata.read(b);

}
if(read==-1){
return ;
}
ps.write(b, 0, read);
ps.flush();
fdata.close();

dis.close();
cs.close();
ss.close();
}
}

}catch (Exception e) {
// TODO: handle exception

}
}






}

 

转载于:https://www.cnblogs.com/weeds/archive/2012/02/10/2344849.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值