java设计一个基于TCP的文件上传功能,将文件从客户端上传到指定服务器。
时间: 2024-03-09 07:44:50 浏览: 21
好的,我可以为您提供一个基本的Java代码示例,用于实现基于TCP的文件上传功能。请参考以下代码:
服务端:
```java
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server is listening...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected: " + socket.getInetAddress().getHostAddress());
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream("server_file.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
socket.close();
System.out.println("File received and saved!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端:
```java
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
OutputStream out = socket.getOutputStream();
InputStream in = new FileInputStream("client_file.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
socket.close();
System.out.println("File uploaded successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个例子中,服务端监听指定端口(8888),客户端连接到服务端并上传文件。服务端接收文件并保存到本地。
需要注意的是,这个代码示例还有一些需要完善的地方,例如添加异常处理、文件名和路径的设置等。
阅读全文