Socket编程实现文件上传.pdf





《Socket编程实现文件上传.pdf》由会员分享,可在线阅读,更多相关《Socket编程实现文件上传.pdf(6页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、 Socket 编程实现文件上传编程实现文件上传 1.情景描述 Server 端监听指定端口,接受 Client 端连接请求。Client 通过发送 connect 请求与 Server端建立 Socket 连接,然后向 Server 发送一个简单文件,Server 接受该文件后存储到指定目录。完成上传后 Server 端主动断开连接。2.Socket 文件上传的编程实现(1)服务器端的实现代码 package server;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io
2、.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import .BindException;import .ServerSocket;import .Socket;import java.text.SimpleDateFormat;import java.util.Date;/*author 苑仁群 *since 2012.6.5 */public class ServerUpload i
3、nt listenPort=11113;/监听端口号 public static void main(String arg)throws Exception ServerUpload server=new ServerUpload();server.acceptConnections();/处理客户端的socket请求 public void acceptConnections()throws Exception try ServerSocket server=new ServerSocket(listenPort);System.out.println(启动服务开始监听);while(tru
4、e)Socket socketConnection=server.accept();/允许连接 handleConnection(socketConnection);/处理客户端请求 catch(BindException e)System.out.println(无法侦听端口:+listenPort);catch(IOException e)System.out.println(无法在端口上创建实例:+listenPort);/对接收文件进行处理 private void handleConnection(Socket socketConnection)throws Exception St
5、ring fileName=null;String thisDateStr=null;try DataOutputStream sendMsg=new DataOutputStream(socketConnection .getOutputStream();String randomId=getResourceId();Date thisDate=new Date();SimpleDateFormat dayFormat=new SimpleDateFormat(MMDD);thisDateStr=dayFormat.format(thisDate);fileName=thisDateStr+
6、randomId;sendMsg.writeUTF(fileName);sendMsg.flush();catch(Exception e)System.out.println(发送消息错误+n);return;DataInputStream inputStream=null;try inputStream=new DataInputStream(new BufferedInputStream(socketConnection.getInputStream();catch(Exception e)e.printStackTrace();if(inputStream!=null)inputStr
7、eam.close();System.out.print(接收消息缓存错误n);throw e;try String savePath=C:uploadFile;int bufferSize=8192;byte buf=new bytebufferSize;int passedlen=0;long len=0;String passFileName=inputStream.readUTF();int lastIndex=passFileName.lastIndexOf(.);String exName=passFileName.substring(lastIndex,passFileName
8、.length();File thePath=new File(savePath+thisDateStr);if(!thePath.exists()thePath.mkdir();savePath+=thisDateStr+fileName+exName;DataOutputStream fileOut=new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath);len=inputStream.readLong();System.out.println
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Socket 编程 实现 文件 上传

限制150内