1、编写一个服务器端程序,用来接收图片。创建一个监听指定端口号的ServerSocket服务端对象,在while(true)无限循环中持续调用ServerSocket的accept()方法来接收客户端的请求,每当和一个客户端建立连接后,就开启一个新的线程和这个客户端进行交互。在处理文件上传功能的ServerThread线程管理类中,先进行客户端文件上传保存处理,确定了文件保存目录和文件命名方式,然后进行保存处理,最后又通过客户端输出流,向客户端输出“上传成功”的信息进行响应。从运行结果可以看出,服务器端进入阻塞状态,等待客户端连接。
相关代码
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class ServerThread implements Runnable {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
String ip = socket.getInetAddress().getHostAddress();
int count = 1;
try {
File parentFile = new File("D:\\upload\\");
if (!parentFile.exists()) {
parentFile.mkdir();
}
File file = new File(parentFile, ip + "(" + count + ").jpg");
while (file.exists()) {
file = new File(parentFile, ip + "(" + (count++) + ").jpg");
}
InputStream in = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
OutputStream out = socket.getOutputStream();
out.write("上传成功".getBytes());
in.close();
fos.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class UploadTCPServer {
public static void main(String[] args) throws Exception {
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(10001);
while (true) {
Socket client = serverSocket.accept();
new Thread(new ServerThread(client)).start();
}
}
}
2、创建了Socket对象,指定连接服务器的IP地址和端口号,然后分别通过Socket的输出流对象向服务端上传图片和输入流对象获取服务端响应信息。其中,向服务端上传的源图片地址为D:\1.jpg,即D盘根目录下的1.jpg图片,在上传之前一定要确保图片存在。另外,在向服务端上传完毕图片后要调用Socket的shutDownOutput()方法。关闭客户端的输出流。
相关代码
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class UploadTCPClient {
public static void main(String[] args) throws Exception {
Socket client = new Socket(InetAddress.getLocalHost(),10001);
OutputStream out = client.getOutputStream();
FileInputStream fis = new FileInputStream("D:\\1.jpg");
byte[] buf = new byte[1024];
int len= 0;
System.out.println("连接到服务器端,开始文件上传!");
while ((len = fis.read(buf)) != -1) {
out.write(buf, 0, len);
}
client.shutdownOutput();
InputStream is = client.getInputStream();
byte[] bufMsg= new byte[1024];
int len2 = is.read(bufMsg);
while (len2 != -1){
System.out.println(new String(bufMsg, 0, len2));
len2 = is.read(bufMsg);
}
out.close();
is.close();
fis.close();
client.close();
}
}
3、运行结果如下: