[Socket]Socket文件传输

时间:2022-09-26 20:23:31

1、Server

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; public class Server
{
private ServerSocket serverSocket; private DataInputStream in; private FileOutputStream out; public Server(int port) throws IOException
{
serverSocket = new ServerSocket();
} public void receiveFile(String destFile) throws IOException
{
Socket socket = serverSocket.accept();
DataInputStream in = new DataInputStream(socket.getInputStream()); out = new FileOutputStream(destFile);
int length = in.readInt();
System.out.println("receiveLength:"+length); byte[] buffer = new byte[];
int end = ;
while ((end = in.read(buffer)) > )
{
out.write(buffer, , end);
out.flush();
}
}
public void close()
{
try{
try{
if (in != null) in.close();
}
finally{
try{
if (out != null) out.close();
}
finally{
serverSocket.close();
}
}
}catch (IOException e){
// ignore
} } public static void main(String[] args) throws IOException
{
Server server = new Server();
try{
server.receiveFile("c:/dest.txt");
}finally{
server.close();
}
}
}

2、Client

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException; public class Client
{
private Socket socket; private FileInputStream input; private DataOutputStream output; public Client(String IP, int port) throws UnknownHostException, IOException
{
this.socket = new Socket(IP, port);
output = new DataOutputStream(socket.getOutputStream());
} public void sendFile(String fileName) throws IOException
{
input = new FileInputStream(fileName);
// 获得文件长度
int fileLength = input.available();
System.out.println("file length:" + fileLength);
output.writeInt(fileLength);
// 读取文件,写入socket
byte[] buffer = new byte[];
int bufferLength = ;
while ((bufferLength = input.read(buffer)) > )
{
output.write(buffer, , bufferLength);
}
} public void close()
{
try{
try{
if (input != null) input.close();
}
finally{
try{
if (output != null) output.close();
}
finally{
socket.close();
}
}
}catch (IOException e){
// ignore
} } public static void main(String[] args) throws UnknownHostException, IOException
{
Client client = new Client("127.0.0.1", );
try
{
client.sendFile("c:/src.txt");
}
finally
{
client.close();
}
}
}