java socket文件传输代码示例
时间: 2023-10-09 07:17:50 浏览: 89
Java socket文件传输实例
5星 · 资源好评率100%
以下是一个简单的Java Socket文件传输代码示例:
// 服务器端代码
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
InputStream inputStream = clientSocket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("received_file.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
clientSocket.close();
serverSocket.close();
}
}
// 客户端代码
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 4444);
File file = new File("file_to_send.txt");
FileInputStream fileInputStream = new FileInputStream(file);
OutputStream outputStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
outputStream.close();
socket.close();
}
}
这个示例中,服务器监听端口4444,并等待客户端连接。客户端连接到服务器并打开一个文件,将其内容通过Socket发送给服务器。服务器接收数据并将其写入一个名为“received_file.txt”的文件。请注意,这个示例没有错误处理和验证代码,仅作为演示用途。
阅读全文