//------------------------------------------------------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();
}
}
}
}
上面的代码的功能是服务端向连接到服务端的客户端传送图片,
思路很简单,就是服务端通关字节流的形式向客户端传送数据,然后客户端接收数据并写到相应位置。