本文通過完整的代碼示例,展示如何使用 Java Socket 實現伺服器與客戶端之間的文件傳輸功能。包含伺服器端、客戶端及通用工具類的實現。
伺服器監聽指定端口,接受客戶端連接後,讀取本地文件並通過輸出流發送給客戶端。
package sterning;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
int port = 8821;
void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 待傳輸文件路徑
String filePath = "D:\\lib.rar";
File fi = new File(filePath);
System.out.println("文件長度:" + (int) fi.length());
// 阻塞等待客戶端連接
s = ss.accept();
System.out.println("建立 socket 連接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte(); // 簡單握手
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
// 發送文件名與長度
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();
// 分塊發送文件內容
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 關閉資源
fis.close();
s.close();
System.out.println("文件傳輸完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String arg[]) {
new ServerTest().start();
}
}
封裝連接建立、消息發送、流獲取與關閉等通用操作。
package sterning;
import java.io.*;
import java.net.*;
public class ClientSocket {
private String ip;
private int port;
private Socket socket = null;
DataOutputStream out = null;
DataInputStream getMessageStream = null;
public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null) socket.close();
throw e;
}
}
public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null) out.close();
throw e;
}
}
public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null) getMessageStream.close();
throw e;
}
}
public void shutDownConnection() {
try {
if (out != null) out.close();
if (getMessageStream != null) getMessageStream.close();
if (socket != null) socket.close();
} catch (Exception e) { }
}
}
客戶端連接伺服器,發送簡單指令後接收文件流並保存到本地。
package sterning;
import java.io.*;
public class ClientTest {
private ClientSocket cs = null;
private String ip = "localhost";
private int port = 8821;
private String sendMessage = "Windows";
public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("連接伺服器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("連接伺服器失敗!" + "\n");
return false;
}
}
private void sendMessage() {
if (cs == null) return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("發送消息失敗!" + "\n");
}
}
private void getMessage() {
if (cs == null) return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息緩存錯誤\n");
return;
}
try {
String savePath = "E:\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len = 0;
savePath += inputStream.readUTF(); // 文件名由伺服器傳來
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(savePath)));
len = inputStream.readLong();
System.out.println("文件的長度為:" + len + "\n");
System.out.println("開始接收文件!" + "\n");
while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
System.out.println("文件接收了" + (passedlen * 100 / len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存為" + savePath + "\n");
fileOut.close();
} catch (Exception e) {
System.out.println("接收消息錯誤" + "\n");
return;
}
}
public static void main(String arg[]) {
new ClientTest();
}
}
ServerSocket.accept() 阻塞等待連接。BufferedInputStream/OutputStream 提高 I/O 效率。