创建服务端:
public class TcpFileServer {
public static void main(String[] args) throws Exception {
//1创建ServerSocket
ServerSocket listener=new ServerSocket(9999);
//2侦听,接收客户端请求
System.out.println("服务器已启动.........");
Socket socket=listener.accept();
//3获取输⼊流
InputStream is=socket.getInputStream();
//4边读取,边保存
FileOutputStream fos=new FileOutputStream("d:\\002.jpg");
byte[] buf=new byte[1024*4];
int count=0;
while((count=is.read(buf))!=-1) {
fos.write(buf,0,count);
}
//5关闭
fos.close();
is.close();
socket.close();
listener.close();
System.out.println("接收完毕");
}
}
创建发送端(客户端):
public class TcpFileClient {
public static void main(String[] args) throws Exception { //1创建Socket
Socket socket=new Socket("192.168.0.103", 9999); //2获取输出流
OutputStream os=socket.getOutputStream(); //3边读取⽂件,边发送
FileInputStream fis=new FileInputStream("d:\\001.jpg");
byte[] buf=new byte[1024*4];
int count=0;
while((count=fis.read(buf))!=-1) {
os.write(buf,0,count);
} //4关闭
fis.close();
os.close();
socket.close();
System.out.println("发送完毕");
}
}