java socket网络编程以及文件流的使用
一、公共类 FileInfo.java
public class FileInfo {
private String filePath;
private String fileType;
public FileInfo(String filePath, String fileType) {
this.filePath = filePath;
this.fileType = fileType;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getFileInfo(){
return this.filePath+"."+this.fileType;
}
}
二、服务器 Server.java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
FileInfo filePath = new FileInfo("d:\\毛不易-消愁 (明日之子 第7期)(高清)","mp4");
File file = new File(filePath.getFileInfo());
FileInputStream ins01 = new FileInputStream(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] fileByte = new byte[1024];
int readLen = 0;
while((readLen = ins01.read(fileByte))!=-1){
byteArrayOutputStream.write(fileByte,0,readLen);
}
fileByte = byteArrayOutputStream.toByteArray();
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("本机端口9999正在监听.......");
Socket socket = serverSocket.accept();
OutputStream ios = socket.getOutputStream();
ios.write(fileByte);
socket.shutdownOutput();
System.out.println("服务端文件传出完成");
byteArrayOutputStream.close();
ios.close();
ins01.close();
socket.close();
serverSocket.close();
}
}
三、客户端 Client.java
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class Client{
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(),9999);
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] buffer = new byte[1024];
int readLen;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((readLen = bis.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, readLen);
}
byte[] bytes = byteArrayOutputStream.toByteArray();
FileOutputStream fileOutputStream = new FileOutputStream("d:\\temp.mp4");
fileOutputStream.write(bytes);
byteArrayOutputStream.close();
fileOutputStream.close();
bis.close();
socket.close();
}
}