简单的基于JAVA Socket 文件传输

package server;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.Socket;

public class Cline {

	public static void main(String[] args) throws IOException {
		// TODO 自动生成的方法存根
		File file=new File("d:\\test1.txt");
		file.createNewFile();
		RandomAccessFile raf= new RandomAccessFile(file, "rw");
		Socket server=new Socket("127.0.0.1",60000);
		InputStream netIn=server.getInputStream();
		InputStream in=new DataInputStream(new BufferedInputStream(netIn));
		byte [] buf=new byte[2048];
		int num=in.read(buf);
		while(num!=-1)
		{
			raf.write(buf, 0, num);
			raf.skipBytes(num);
			num=in.read(buf);
		}
		in.close();
		raf.close();
		System.out.println("客户端接受文件完毕");

	}

}

服务器端:

package cline;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class Server {

	public static void main(String[] args) throws IOException, IOException {
		String  fileName="D:\\test1.xml";
		File file=new File(fileName);
		FileInputStream  fos=new FileInputStream(file);
		ServerSocket ss=new ServerSocket(60000);
		Socket client=ss.accept();
		OutputStream netOut=client.getOutputStream();
		OutputStream  doc=new DataOutputStream(new BufferedOutputStream(netOut));
		byte [] buf=new byte[2048];
		int num=fos.read(buf);
		while(num!=-1)
		{
			doc.write(buf, 0, num);
			doc.flush();
			num=fos.read(buf);
		}
		fos.close();
		doc.close();
		System.out.println("文件传送完毕");
		

	}

}


你可能感兴趣的:(java)