scoket
客户端
package vedio.socket; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.InetSocketAddress; import java.net.Socket; public class Client { public static void main(String[] args) { int length = 0; byte[] sendByte = null; Socket socket = null; DataOutputStream dout = null; FileInputStream fin = null; try { try { socket = new Socket(); socket.connect(new InetSocketAddress("127.0.0.1", 5555),10 * 1000); dout = new DataOutputStream(socket.getOutputStream()); File file = new File("E:\\xx\\xx.docx"); fin = new FileInputStream(file); sendByte = new byte[1024]; dout.writeUTF(file.getName()); while((length = fin.read(sendByte, 0, sendByte.length))>0){ dout.write(sendByte,0,length); dout.flush(); } } catch (Exception e) { } finally{ if (dout != null) dout.close(); if (fin != null) fin.close(); if (socket != null) socket.close(); } } catch (Exception e) { e.printStackTrace(); } } }
服务端
package vedio.socket; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server implements Runnable{ @Override public void run() { // TODO Auto-generated method stub } public static void main(String[] args) { try { final ServerSocket server = new ServerSocket(5555); Thread th = new Thread(new Runnable() { @Override public void run() { while(true){ System.out.println("开始监听。。。。。。。"); Socket socket; try { socket = server.accept(); System.out.println("有连接"); receiveFile(socket); } catch (IOException e) { e.printStackTrace(); } } } }); th.run(); } catch (Exception e) { e.printStackTrace(); } } public static void receiveFile(Socket socket) { byte[] inputByte =null; int length = 0; DataInputStream din = null; FileOutputStream fout = null; try { din = new DataInputStream(socket.getInputStream()); fout = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\"+din.readUTF())); inputByte = new byte[1024]; System.out.println("开始接受数据"); while(true){ if(din!=null){ length = din.read(inputByte,0,inputByte.length); } if(length==-1){ break; } fout.write(inputByte, 0, length); fout.flush(); } System.out.println("完成接受"); } catch (IOException e) { e.printStackTrace(); }finally { if (fout != null) try { fout.close(); if (din != null) din.close(); if (socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
//参考资料:http://www.cnblogs.com/feiyun126/p/3921466.html