Java利用socket传输文件

//------------------------------------------------------Server------------------------------------------------------------//
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{
	public static void main(String[] args)
	{
		ServerSocket server = null;
		Socket socket = null;
		DataOutputStream dout = null;
		File file = new File("D:\\1.jpg");//要读取的文件的路径
		FileInputStream fin = null;
		byte[] inByte = new byte[1024];
		int length = 0;
		try
		{
			server = new ServerSocket(7778);
			socket = server.accept();
			dout = new DataOutputStream(socket.getOutputStream());
			fin = new FileInputStream(file);
			
			while((length = fin.read(inByte, 0, inByte.length)) != -1)
			{
				dout.write(inByte, 0, length);
				dout.flush();
			}
			
		} 
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			try
			{
				server.close();
				socket.close();
				fin.close();
				dout.close();
			} 
			catch (IOException ex) 
			{
				ex.printStackTrace();
			}
		}
	}
}




//------------------------------------------------------Client------------------------------------------------------------//
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client
{
	public static void main(String[] args)
	{
		Socket socket = null;
		File file = new File("D:\\2.jpg");//保存接收文件的路径
		FileOutputStream fout = null;
		DataInputStream din = null;
		byte[] outByte = new byte[1024];
		int length = 0;
		
		try
		{
			socket = new Socket("127.0.0.1", 7778);//服务的端的IP,默认为本机地址
			din = new DataInputStream(socket.getInputStream());
			fout = new FileOutputStream(file);
			
			while((length = din.read(outByte, 0, outByte.length)) != -1)
			{
				fout.write(outByte, 0, length);
				fout.flush();
			}
		} 
		catch (IOException ex) 
		{
			ex.printStackTrace();
		}
		finally
		{
			try
			{
				socket.close();
				fout.close();
				din.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}	
	}
}


上面的代码的功能是服务端向连接到服务端的客户端传送图片,

思路很简单,就是服务端通关字节流的形式向客户端传送数据,然后客户端接收数据并写到相应位置。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值