多用户图片上传代码

来源:互联网 发布:java break用法 编辑:程序博客网 时间:2024/05/22 11:54
package com.neutron.network.tcp.thread;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;/** * 图片上传多线程类 * @author zhanght * */public class PictureThread implements Runnable {/** * 客户端socke服务 */private Socket socket;public PictureThread(Socket socket) {this.socket = socket;}@Overridepublic void run() {int count = 0;String filePath = "/home/zhanght/";try {// 获取客户端信息String hostName = socket.getInetAddress().getHostName();// 获取客户端服务输入流InputStream in = socket.getInputStream();// 定义图片接收文件File file = new File(filePath + hostName + "(" + count + ").jpg");while (file.exists()) {file = new File(filePath + hostName + "(" + count++ + ").jpg");}// 创建文件输出流FileOutputStream fos = new FileOutputStream(file);// 创建缓冲区byte[] buff = new byte[1024];int len = 0;while ((len = in.read(buff)) != -1) {fos.write(buff, 0, len);}// 获取客户端服务输出流OutputStream out = socket.getOutputStream();out.write("图片上传成功".getBytes());out.close();fos.close();in.close();socket.close();} catch (IOException e) {e.printStackTrace();}}}
package com.neutron.network.tcp.thread;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class PictureServer {/* * 此时服务器端有局限,即必须执行一个一个地进行图片上传。不能同时上传多个文件。 * 例如,当a客户端连接后,被服务器端获取,服务器端执行具体流程;此时如果b客户端连接,只能进行等待。 * 因为此时服务器端还没有处理完a客户端请求。  */@SuppressWarnings("resource")public static void main(String[] args) throws IOException {// 建立服务端的服务,ServerSocket,服务端服务绑定端口ServerSocket server = new ServerSocket(10008);while (true) {Socket socket = server.accept();System.out.println("client ip ::" + socket.getInetAddress().getHostAddress());new Thread(new PictureThread(socket)).start();}}}

package com.neutron.network.tcp.thread;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;/** * 图片上传客户端 * @author zhanght * */public class PictureClient {public static void main(String[] args) throws UnknownHostException, IOException {// 创建客户端,并且绑定服务器主机和端口号Socket client = new Socket("127.0.0.1", 10008);// 定义文件输入流FileInputStream fis = new FileInputStream("/home/zhanght/Pictures/001.png");// 获取客户端输出流OutputStream out = client.getOutputStream();// 向服务器端发送文件int len = 0;while ((len = fis.read()) != -1) {out.write(len);}// 添加文件结束标识,-1client.shutdownOutput();// 获取客户端输入流InputStream in = client.getInputStream();byte[] buff = new byte[1024];in.read(buff);System.out.println("server return::" + new String(buff));in.close();out.close();fis.close();client.close();}}
0 0
原创粉丝点击