利用socket实现自动上传文件

一:socket服务端,在web服务器启动时启动该服务端

public class FileSocketServer {
	public void start(){
              final int port = PropertiesUtils.getInt("socketPort");//从配置文件中获取端口
		new Thread(){
			@Override
			public void run() {
				try {
					ServerSocket server = new ServerSocket(port);
					ExecutorService pool = Executors.newFixedThreadPool(10);
					while (true) {
						try {  
							System.out.println("开始监听...");
							Socket socket = server.accept();
							System.out.println("有客户端链接");
							pool.execute(new Service(socket));
						} catch (Exception e) {
							System.out.println("服务器异常");
							e.printStackTrace();
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}.start();
	}
	
	class Service extends Thread{
		Socket socket;
		public Service(Socket socket){
			this.socket = socket;
		}
		@Override
		public void run() {
			String suffix = "";
			try {
				DataInputStream dis = new DataInputStream(socket.getInputStream());
				String line;
				while((line = readLine(dis)) != null){
					if(line.startsWith("filesuffix")){
						suffix = line.substring(11);
					}else if("file".equals(line)){
						service(suffix,dis);
						break;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		private String readLine(DataInputStream dis) throws IOException{
			byte[] buf = new byte[]{};
			int n;
			int prev =0;
			while((n = dis.read()) > 0){
				if( n == '\r'){
				}else if( n == '\n' && prev == '\r')
					break;
				else{
					buf = Arrays.copyOf(buf, buf.length+1);
					buf[buf.length-1] = (byte)n;
				}
				prev = n;
			}
			return new String(buf);
		}
		
		private void service(String suffix,DataInputStream dis){
			int length = 0;
			FileOutputStream fos = null;
			DataOutputStream dos = null;
			String filePath = "F:/"+System.currentTimeMillis()+"_"+new Random().nextInt(100)+"."+suffix;
			try {
				try {
					/* 文件存储位置 */
					fos = new FileOutputStream(new File(filePath));    
					byte[] inputByte = new byte[1024];   
					System.out.println("开始接收数据...");  
					while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {
						fos.write(inputByte, 0, length);
						fos.flush();    
					}
					System.out.println("完成数据接收:"+filePath);
					//
					System.out.println("响应客户端……");
					dos = new DataOutputStream(socket.getOutputStream());
					dos.write((filePath+"\r\n").getBytes());
					dos.flush();
					System.out.println("数据发送完毕");
				} finally {
					if (fos != null)	fos.close();
					if(dis != null)		dis.close();
					if(dos != null)		dos.close();
					if(socket != null)	socket.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
}

二:socket客户端

public class FileSocketClient {
	public String start(String filepath){
		Socket socket = new Socket();  
		try {
                     //从配置文件获取服务器IP和端口
			String serverIP = PropertiesUtils.getString("socketServerIP");
			int port = PropertiesUtils.getInt("socketPort");
			socket.connect(new InetSocketAddress(serverIP, port));
			String serverPath = new SocketClient(socket,filepath).call();
			return serverPath;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	class SocketClient implements Callable<String>{
		Socket socket;
		String filepath;
		public SocketClient(Socket socket,String filepath){
			this.socket = socket;
			this.filepath = filepath;
		}
		@Override
		public String call() {
			try {
				OutputStream os = socket.getOutputStream();
				os.write("filesuffix:jpg\r\n".getBytes());
				os.write("file\r\n".getBytes());
				return service();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return "";
		}
		private String service(){
			DecimalFormat df = new DecimalFormat("00.00");
			int length = 0;
			double sumL = 0 ;
			DataOutputStream dos = null;
			Scanner console = null;
			FileInputStream fis = null;
			boolean bool = false;
			try {
				File file = new File(filepath); //要传输的文件路径
				long l = file.length(); 
				dos = new DataOutputStream(socket.getOutputStream());
				fis = new FileInputStream(file);      
				byte[] sendBytes = new byte[1024];  
				while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
					sumL += length;  
					System.out.println("已传输:"+df.format(((sumL/l)*100))+"%");
					dos.write(sendBytes, 0, length);
					dos.flush();
				} 
				if(sumL==l){
					bool = true;
				}
				socket.shutdownOutput();
				//输入流  
				console = new Scanner(socket.getInputStream());  
	                        //接收服务器的相应  
	                        String line = console.nextLine();
	                        return line;
			}catch (Exception e) {
				System.out.println("客户端文件传输异常");
				bool = false;
				e.printStackTrace();  
			} finally{  
				try {
					if (dos != null)	dos.close();
					if (fis != null)	fis.close();   
					if(console != null)	console.close();
					if (socket != null)	socket.close();    
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			System.out.println(bool?"成功":"失败");
			return "";
		}
	}

}

三:自动上传文件jsp

<%@page contentType="text/html;charset=utf-8" pageEncoding="UTF-8"%>
<%@page import="com.util.socket.FileSocketClient" %>
<%
String filepath = request.getParameter("filepath");
String code = request.getParameter("uniqueCode");
String uniqueCode = (String)session.getAttribute("uniquetag");
//条件判断 
if(filepath != null && uniqueCode != null && uniqueCode.equals(code)){
	String serverpath = new FileSocketClient().start(filepath);
	response.getWriter().print(serverpath);
}
%>

下面是个测试小实例

前台jsp表单

<head>
		<title></title>
		<script type="text/javascript" src="${ctx}/js/jquery-1.7.2.js"></script>
		<script type="text/javascript">
			function upload(){
				var code = $("#unq").val();
				$.ajax({
					url:"${ctx}/autoupload.jsp",
					data:"filepath=F:/my.jpg&uniqueCode="+code,
					type:"post",
					dataType:"text",
					async:false,
					success:function(data){
						$("#objform").append("<input type='hidden' name='filepath' value='"+data+"'/>");
					}
				});
				return true;
			}
		</script>
	</head>
	<body>
		<form action="${ctx }/autoupload.action" method="post" οnsubmit="return upload()" id="objform">
			<!-- 随机生成唯一字符串并保存在session中  -->
                     <jt:unique id="unq"/>
			<input name="name"/><br/>
			<input name="age"/><br/>
			<input type="submit" value="提交"/>
		</form>
		
	</body>

后台Action

public String autoUpload() throws Exception{
		String path = request.getParameter("filepath");
		System.out.println(path);
		System.out.println(request.getParameter("name"));
		System.out.println(request.getParameter("age"));
		return SUCCESS;
}
OK啦,在action中可以获取文件上传到服务器后的file地址


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于JAVA CS远程监控系统软件的实现(源代码+WORD论文文档论文) 基于JAVA C/S远程监控系统软件的实现 摘 要 近年来,网络技术的不断发展,为远程监控技术的发展创造了条件。远程监控系统软件越来越受到人们的重视,其实用性也毋庸质疑。基于JAVA C/S远程监控系统软件突破了空间的限制,使用者不用亲临,在自己的电脑面前就能轻松的实现对被监控端机器的监控。本系统采用Java网络编程和Java图形编程实现。笔者在开发过程中将网络技术与远程监控理论基础相结合,实现了以下功能:能连续获得被监控端机器屏幕变化;实现被监控端硬盘文件的上传、下载;实现对鼠标、键盘的模拟;实现在远程机器上执行任意DOS命令;远程关机、远程重启计算机,方便了用户监视和操作被监控端机器。本系统从系统需求分析、概要设计、详细设计到具体的编码实现和后期的代码优化、功能测试都严格遵循了软件工程的思想。 关键词:远程监控;Java Robot;屏幕截取;Java Socket 系统需求分析及理论基础 2.1 系统需求分析 2.1.1 系统功能需求 1.连续获得被控端机器屏幕变化。 2.实现被控端硬盘文件的上传、下载。 3.实现对鼠标、键盘的模拟。 4.实现在被控端机器上执行任意DOS命令。 5.远程关机、远程重启计算机。 2.1.2 其他需求 1.系统实用,界面操作简便。 2.被监控端自动隐藏运行。 被监控端将随电脑启动而自动运行,运行时默认无任何可见界面。 2.2 系统开发原理及关键技术 2.2.1 系统开发原理 本系统是利用类java.awt.robot中的屏幕截取和鼠标、键盘自动控制功能,然后加上网络传输功能来完成来完成截屏和远程控制的。 2.2.2 系统运行概述 1.启动被监控端,打开指定的UDP端口号。用于读取命令。 2.被监控端读取命令(命令格式为ordername:port)ordername为命令名字,port为主控端打开的TCP端口。 3.接到主控端连接后,被监控端就对当前用户的桌面采用屏幕截取,然后发送给主控端。依被监控端设计的不同,可以设定屏幕截取的时间间隔,时间间隔短一点就可以获得连续屏幕变化了。 4.主控端在画布上对鼠标、键盘事件进行监听,被监控端重演主控端上的事件 5.主控端和被监控端读取和发送数据,分别来实现文件上传和下载。 6.在被监控端实现DOS命令的执行。 2.2.3 系统的关键技术 系统使用的关键技术就是Java网络编程和Java图形编程。用Java网络编程实现主控端和被监控端的通讯(命令收发、数据传送),用Java图形编程完成主控端控制界面的编写。具体应用如下: 1.实现主控端(服务器)与被监控端(客户端)之间的通讯。 ——用Java Socket实现。 2.用Java采集事件,封装成消息,用于发送。 ——在主控端机器上采集事件(一般只不过是键盘和鼠标的事件),然后封装成消息类传输到被监控端。 3.在被监控端上重演主控端的动作事件。 ——在被监控端运行client端,接收消息,如果主控端有请求操作的消息,用Robot截下当前屏幕,传给主控端,主控端显示被监控端的屏幕,是一个位图;然后接收在这个位图上的鼠标事件和键盘事件,并把鼠标位置(位图上的坐标换算成对应的屏幕上的坐标)和键值送到被监控端上,在被监控端上重演同样的事件。 2.3 系统的开发平台 JDK1.5.0,Eclipse3.1,Windows XP Professional 2.3.1 Eclipse介绍 Eclipse是一种可扩展的开放源代码IDE。2001年11月,IBM公司捐出价值4,000万美元的源代码组建了Eclipse联盟,并由该联盟负责这种工具的后续开发。集成开发环境(IDE)经常将其应用范围限定在“开发、构建和调试”的周期之中。为了帮助集成开发环境 (IDE)克服目前的局限性,业界厂商合作创建了Eclipse平台。Eclipse允许在同一IDE中集成来自不同供应商的工具,并实现了工具之间的互操作性,从而显著改

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值