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

}
}






}

 

posted @ 2012-02-10 09:37  狼迹天涯  阅读(267)  评论(0编辑  收藏  举报