資源描述:
《Socket編程實(shí)現(xiàn)文件上傳.pdf》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、Socket編程實(shí)現(xiàn)文件上傳1.情景描述Server端監(jiān)聽指定端口,接受Client端連接請(qǐng)求。Client通過發(fā)送connect請(qǐng)求與Server端建立Socket連接,然后向Server發(fā)送一個(gè)簡(jiǎn)單文件,Server接受該文件后存儲(chǔ)到指定目錄。完成上傳后Server端主動(dòng)斷開連接。2.Socket文件上傳的編程實(shí)現(xiàn)(1)服務(wù)器端的實(shí)現(xiàn)代碼packageserver;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.DataInputStr
2、eam;importjava.io.DataOutputStream;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.net.BindException;importjava.net.ServerSocket;importjava.net.Socket;importjava.text.SimpleDateFormat;importjava.util.Date;/****@author苑仁群*@since2012.6.5*/publi
3、cclassServerUpload{intlistenPort=11113;//監(jiān)聽端口號(hào)publicstaticvoidmain(Stringarg[])throwsException{ServerUploadserver=newServerUpload();server.acceptConnections();}//處理客戶端的socket請(qǐng)求publicvoidacceptConnections()throwsException{try{ServerSocketserver=newServerSocket(listenPort);System.ou
4、t.println("啟動(dòng)服務(wù)開始監(jiān)聽……");while(true){SocketsocketConnection=server.accept();//允許連接handleConnection(socketConnection);//處理客戶端請(qǐng)求}}catch(BindExceptione){System.out.println("無法偵聽端口:"+listenPort);}catch(IOExceptione){System.out.println("無法在端口上創(chuàng)建實(shí)例:"+listenPort);}}//對(duì)接收文件進(jìn)行處理privatevoidh
5、andleConnection(SocketsocketConnection)throwsException{StringfileName=null;StringthisDateStr=null;try{DataOutputStreamsendMsg=newDataOutputStream(socketConnection.getOutputStream());StringrandomId=getResourceId();DatethisDate=newDate();SimpleDateFormatdayFormat=newSimpleDateFormat
6、("MMDD");thisDateStr=dayFormat.format(thisDate);fileName=thisDateStr+randomId;sendMsg.writeUTF(fileName);sendMsg.flush();}catch(Exceptione){System.out.println("發(fā)送消息錯(cuò)誤"+"");return;}DataInputStreaminputStream=null;try{inputStream=newDataInputStream(newBufferedInputStream(socketCon
7、nection.getInputStream()));}catch(Exceptione){e.printStackTrace();if(inputStream!=null)inputStream.close();System.out.print("接收消息緩存錯(cuò)誤");throwe;}try{StringsavePath="C:\uploadFile\";intbufferSize=8192;byte[]buf=newbyte[bufferSize];intpassedlen=0;longlen=0;StringpassFileName=inpu
8、tStream.readUTF();intlastIndex=pa