基于socket的簡單文件傳輸系統

【實驗目的及要求】

Uinx/Linux/Windows 環境下通過 socket 方式實現一個基于 Client/Server?文件傳輸程序。

【實驗原理和步驟】

1. 確定傳輸模式:通過 socket 方式實現一個基于 Client/Server P2P 模式的文件傳輸程序。

2. 如果選擇的是 Client/Server 模式的文件傳輸程序,則需要分別實現客戶端和服務器端程序。客戶端:用面向連接的方式實現通信。采用 Socket 類對象,接收服務器發送的文件并保存在特定的位置。服務器端:監聽客戶請求,讀取磁盤文件并向客戶端發送文件。注意:需要實現文件的讀寫操作。


【方案設計】


1)編寫基于socket的文件傳輸系統中的public?class server

2)將server中需要調用到的類與方法集合在public?class FileTransfer extends Thread中;

3)在FileTransfer中完成ReceiveFile()SendFile()方法的聲明;

4)編寫客戶端程序 public?class client,在類client中完成主要用到的方法DownloadFile()UploadFile()方法的聲明;

5)在ubuntu虛擬終端中利用java虛擬機對程序進行運行調試。



【實驗環境】

ubuntu 12.04

java version "1.7.0_17"

Eclipse Platform Version: 4.2.1

?

怪無聊的,最初想寫的是p2p文件分享系統,結果項目老師一個催促,讓我心跳加快=。=什么都顧不上了,草草了事。。。不說廢話了,這實驗不難,直接上源碼。

server

?

 1 import java.io.BufferedReader;
 2 import java.io.DataInputStream;
 3 import java.io.DataOutputStream;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 
 9 /**
10  * Server of a file sharing system based on socket
11  * @author alex
12  *
13  */
14 
15 public class server {
16 
17     
18     public static void main(String[] args) throws IOException{
19         int PortNum;
20         InputStreamReader is=new InputStreamReader(System.in);
21         BufferedReader br=new BufferedReader(is);
22         System.out.print("Enter the port number: ");
23         PortNum=Integer.parseInt(br.readLine().trim());
24         ServerSocket ss=new ServerSocket(PortNum);
25         while(true){
26             System.out.println("Server get ready at port "+PortNum+"\nWaiting for connection");
27             FileTransfer ft=new FileTransfer(ss.accept());
28         }
29     }
30     
31 }
View Code

?

?

FileTransfer

  1 import java.io.DataInputStream;
  2 import java.io.DataOutputStream;
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.net.Socket;
  8 
  9 /**
 10  * FileTransfer of a file sharing system based on socket, of which the methods are used in the server
 11  * @author alex
 12  *
 13  */
 14     public class FileTransfer extends Thread{
 15 
 16         DataInputStream dis;
 17         DataOutputStream dos;
 18         Socket client_socket;
 19         
 20         public FileTransfer(Socket socket){
 21             client_socket=socket;
 22             try {
 23                 dis=new DataInputStream(client_socket.getInputStream());
 24                 dos=new DataOutputStream(client_socket.getOutputStream());
 25                 System.out.println("Socket connected");
 26                 start();
 27             } catch (IOException e) {
 28                 e.printStackTrace();
 29             }
 30             
 31         }
 32         
 33         
 34         public void run(){    
 35             System.out.println("Connection Established");
 36             while(true){
 37                 System.out.println("Waiting for client command... ");
 38                 String cd;
 39                 try {
 40                     cd = dis.readUTF();
 41                     if(cd.equalsIgnoreCase("DOWNLOAD")){
 42                         System.out.println("Client requests to download");
 43                         SendFile();
 44                     }
 45                     else if(cd.equalsIgnoreCase("UPLOAD")){
 46                         System.out.println("Client requests to upload");
 47                         ReceiveFile();
 48                     }
 49                     else if(cd.equalsIgnoreCase("DISCONNECT")){
 50                         System.out.println("Connection shutdown...");
 51                         System.exit(1);
 52                     }
 53                 } catch (IOException e) {
 54                     e.printStackTrace();
 55                 }
 56             }
 57             
 58         }
 59 
 60 
 61         private void ReceiveFile() {
 62             try {
 63                 String write;
 64                 String filename=dis.readUTF();
 65                 File f=new File(filename);
 66                 if(f.exists()){
 67                     dos.writeUTF("File Already Existed");
 68                     write=dis.readUTF();
 69                 }
 70                 else write="Y";
 71                 if(write.equalsIgnoreCase("Y")){
 72                     int ch;
 73                     FileOutputStream fout=new FileOutputStream(f);
 74                     String ttt;
 75                     do{
 76                         ttt=dis.readUTF();
 77                         ch=Integer.parseInt(ttt);
 78                         fout.write(ch);
 79                     }while(ch!=-1);
 80                     fout.close();
 81                     dos.writeUTF("File Uploaded");
 82                 }
 83                 else return;
 84             } catch (IOException e) {
 85                 e.printStackTrace();
 86             }
 87             
 88         }
 89 
 90 
 91         private void SendFile() throws IOException {
 92             String filename=dis.readUTF();
 93             File f=new File(filename);
 94             if(!f.exists()){
 95                 dos.writeUTF("File Not Existed");
 96                 return;
 97             }else{
 98                 dos.writeUTF("Dowloading File "+filename);
 99                 FileInputStream fin=new FileInputStream(f);
100                 int ch;
101                 do{
102                     ch=fin.read();
103                     dos.writeUTF(String.valueOf(ch));
104                 }while(ch!=-1);
105                 fin.close();
106                 dos.writeUTF("File "+filename+" Download Successfully");
107             }
108             
109         }
110         
111     }
View Code

?

client

  1 import java.io.BufferedReader;
  2 import java.io.DataInputStream;
  3 import java.io.DataOutputStream;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.io.InputStreamReader;
  9 import java.net.InetAddress;
 10 import java.net.Socket;
 11 import java.net.UnknownHostException;
 12 
 13 
 14 /**
 15  * Client of a file sharing system based on socket
 16  * @author alex
 17  *
 18  */
 19 public class client {
 20     int PortNum;
 21     BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
 22     DataInputStream dis;
 23     DataOutputStream dos;
 24     
 25     public client() throws UnknownHostException, IOException{
 26         System.out.println("Enter the port number:");
 27         PortNum=Integer.parseInt(bf.readLine().trim());
 28         Socket soc=new Socket(InetAddress.getByName("localhost"),PortNum);
 29         dis=new DataInputStream(soc.getInputStream());
 30         dos=new DataOutputStream(soc.getOutputStream());
 31     }
 32     
 33     public static void main(String[] args) throws UnknownHostException, IOException {
 34         client MyClient=new client();
 35         String option;
 36         while(true){
 37             option=MyClient.display();
 38             switch(option){
 39             case "1":    MyClient.DownloadFile();break;
 40             case "2":    MyClient.UploadFile();break;
 41             case "3":    MyClient.Disconnect();break;
 42                 default: break;
 43             }
 44         }
 45     }
 46     
 47     public String display() throws IOException{
 48         System.out.println("Choose the operation you want to make:");
 49         System.out.println("1.Download A File");
 50         System.out.println("2.Upload A File");
 51         System.out.println("3.Disconnect");
 52         String op=bf.readLine();
 53         return op;
 54     }
 55     
 56     public void UploadFile() throws IOException{
 57         System.out.println("Enter the file name");
 58         String filename=bf.readLine().trim();
 59         File f=new File(filename);
 60         String msg,write;
 61         if(!f.exists()){
 62             System.out.println("The File "+ filename+" Not Found!");
 63             return;
 64         }
 65         else{
 66             dos.writeUTF("UPLOAD");
 67             dos.writeUTF(filename);
 68             msg=dis.readUTF();
 69             if(msg.equalsIgnoreCase("File Already Existed")){
 70                 System.out.println("File Already Existed On Server, Do You Want To Overwrite it?(Y/N)");
 71                 write=bf.readLine();
 72             }
 73             else write="Y";
 74             dos.writeUTF(write);
 75             if(write.equalsIgnoreCase("Y")){
 76                 System.out.println("Uploading File "+filename);
 77                 FileInputStream fin=new FileInputStream(f);
 78                 int ch;
 79                 do{
 80                     ch=fin.read();
 81                     dos.writeUTF(String.valueOf(ch));
 82                 }while(ch!=-1);
 83                 fin.close();
 84                 System.out.println(dis.readUTF());
 85             }
 86         }
 87     }
 88     public void DownloadFile() throws IOException{
 89         System.out.println("Enter the file name");
 90         String filename=bf.readLine().trim();
 91         String msg,write;
 92         dos.writeUTF("DOWNLOAD");
 93         dos.writeUTF(filename);
 94         msg=dis.readUTF();
 95         if(msg.equalsIgnoreCase("File Not Existed")){
 96             System.out.println("File "+filename+" Not Found On Server");
 97             return;
 98         }else{
 99             System.out.println(msg);
100             File f=new File(filename);
101             FileOutputStream fo=new FileOutputStream(f);
102             int ch;
103             String ttt;
104             do{
105                 ttt=dis.readUTF();
106                 ch=Integer.parseInt(ttt);
107                 fo.write(ch);
108             }while(ch!=-1);
109             fo.close();
110             System.out.println(dis.readUTF());
111             return;
112         }
113             
114     }
115     public void Disconnect() throws IOException{
116         dos.writeUTF("DISCONNECT");
117         System.exit(1);
118     }
119 }
View Code

?

?

轉載于:https://www.cnblogs.com/alex-wood/p/3748781.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/376979.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/376979.shtml
英文地址,請注明出處:http://en.pswp.cn/news/376979.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

《GPU高性能編程-CUDA實戰》中例子頭文件使用

《GPU高性能編程-CUDA實戰(CUDA By Example)》中例子中使用的一些頭文件是CUDA中和C中本身沒有的,需要先下載這本書的源碼,可以在:https://developer.nvidia.com/content/cuda-example-introduction-general-purpose-g…

mcq 隊列_人工智能| AI解決問題| 才能問題解答(MCQ)| 套裝1

mcq 隊列1) Which of the following definitions correctly defines the State-space in an AI system? A state space can be defined as the collection of all the problem statesA state space is a state which exists in environment which is in outer spaceA state sp…

Postgresql的HashJoin狀態機流程圖整理

狀態機 可以放大觀看。 HashJoinState Hash Join運行期狀態結構體 typedef struct HashJoinState {JoinState js; /* 基類;its first field is NodeTag */ExprState *hashclauses;//hash連接條件List *hj_OuterHashKeys; /* 外表條件鏈表;list of …

Ajax和Jsonp實踐

之前一直使用jQuery的ajax方法,導致自己對瀏覽器原生的XMLHttpRequest對象不是很熟悉,于是決定自己寫下,以下是個人寫的deom,發表一下,聊表紀念。 Ajax 和 jsonp 的javascript 實現: /*! * ajax.js * …

得到前i-1個數中比A[i]小的最大值,使用set,然后二分查找

題目 有一個長度為 n 的序列 A&#xff0c;A[i] 表示序列中第 i 個數(1<i<n)。她定義序列中第 i 個數的 prev[i] 值 為前 i-1 個數中比 A[i] 小的最大的值&#xff0c;即滿足 1<j<i 且 A[j]<A[i] 中最大的 A[j]&#xff0c;若不存在這樣的數&#xff0c;則 pre…

學習語言貴在堅持

學習語言貴在堅持 轉自&#xff1a;http://zhidao.baidu.com/link?urlr2W_TfnRwipvCDLrhZkATQxdrfghXFpZhkLxqH1oUapLOr8jXW4tScbyOKRLEPVGCx0dUfIr-30n9XV75pWYfK給大家介紹幾本書和別處COPY來的學習C50個觀點 《Thinking In C》&#xff1a;《C編程思想》&#xff1b; 《The…

stl vector 函數_在C ++ STL中使用vector :: begin()和vector :: end()函數打印矢量的所有元素...

stl vector 函數打印向量的所有元素 (Printing all elements of a vector) To print all elements of a vector, we can use two functions 1) vector::begin() and vector::end() functions. 要打印矢量的所有元素&#xff0c;我們可以使用兩個函數&#xff1a;1) vector :: b…

JqueryUI入門

Jquery UI 是一套開源免費的、基于Jquery的插件&#xff0c;在這里記錄下Jquery UI 的初步使用。 第一、下載安裝 下載Jquery,官網&#xff1a;http://jquery.com;  下載Jquery UI&#xff0c;官網&#xff1a;http://jqueryui.com/ Jquery的部署就不說了&#xff0c;說下Jqu…

gp的分布、分區策略(概述)

對于大規模并行處理數據庫來說&#xff0c;一般由單master與多segment組成。 那么數據表的單行會被分配到一個或多個segment上&#xff0c;此時需要想一想分布策略 分布 在gp6中&#xff0c;共有三個策略&#xff1a; 哈希分布 隨機分布 復制分布 哈希分布 就是對分布鍵進行…

[ Java4Android ] Java基本概念

視頻來自&#xff1a;http://www.marschen.com/ 1.什么是環境變量 2.JDK里面有些什么&#xff1f; 3.什么是JRE&#xff1f; 什么是環境變量&#xff1f; 1.環境變量通常是指在操作系統當中&#xff0c;用來指定操作系統運行時需要的一些參數; 2.環境變量通常為一系列的鍵值對&…

_thread_in_vm_Java Thread類的靜態void sleep(long time_in_ms,int time_in_ns)方法,帶示例

_thread_in_vm線程類靜態無效睡眠(long time_in_ms&#xff0c;int time_in_ns) (Thread Class static void sleep(long time_in_ms, int time_in_ns)) This method is available in package java.lang.Thread.sleep(long time_in_ms, int time_in_ns). 軟件包java.lang.Thread…

大規模web服務開發技術(轉)

前段時間趁空把《大規模web服務開發技術》這本書看完了&#xff0c;今天用一下午時間重新翻了一遍&#xff0c;把其中的要點記了下來&#xff0c;權當復習和備忘。由于自己對數據壓縮、全文檢索等還算比較熟&#xff0c;所以筆記內容主要涉及前5章內容&#xff0c;后面的零星記…

IO多路復用的三種機制Select,Poll,Epoll

IO多路復用的本質是通過系統內核緩沖IO數據讓單個進程可以監視多個文件描述符&#xff0c;一旦某個進程描述符就緒(讀/寫就緒)&#xff0c;就能夠通知程序進行相應的讀寫操作。 select poll epoll都是Linux提供的IO復用方式&#xff0c;它們本質上都是同步IO&#xff0c;因為它…

qt中按鈕貼圖

一.QT之QPushButton按鈕貼圖 二.QT之QToolButton按鈕貼圖 一.QT之QPushButton按鈕貼圖具體操作流程 1. Qt Designer中拖入一Tool Button 2. 選擇圖標的圖片放入工程目錄下&#xff0c;如放在Resources內 3. 雙擊工程的Resource Files下的qrc文件&#xff0c;如圖 4. 在彈出的窗…

Ubuntu手動編譯gVim7.3修復終端啟動時與ibus的沖突

個bug伴隨著Ubuntu/ibus的升級苦憋已久&#xff0c;癥狀為終端啟動gvim時卡死&#xff0c;gvim -f可以緩解此問題&#xff0c;但偶爾還是要發作&#xff0c;況且每次末尾托個&也不方便。其實新版gvim已經修復此bug&#xff0c;不過ubuntu安裝包一直沒更新&#xff0c;那我們…

Android Activity類講解(一)

--by CY[kotomifigmail.com] &#xff11;&#xff0e;protected void onCreate(Bundle savedInstanceState) { throw new RuntimeException("Stub!");   } 當創建一個Activity時&#xff0c;系統會自動調用onCreate方法來完成創建工作&#xff0e;該創建工作包括布…

Mysql的undo、redo、bin log分析

目錄關于undo log關于redolog關于binlog一個事務的提交流程undo log :記錄數據被修改之前的樣子 redo log&#xff1a;記錄數據被修改之后的樣子 bin log&#xff1a;記錄整個操作。 關于undo log 關于undo log&#xff1a; 在執行一條涉及數據變更的sql時&#xff0c;在數據…

typedef 字符串_typedef在C中使用字符數組(定義別名來聲明字符串)的示例

typedef 字符串Here, we have to define an alias for a character array with a given number of maximum characters length to read strings? 在這里&#xff0c;我們必須為具有給定最大字符長度數的字符數組定義別名&#xff0c;以讀取字符串 &#xff1f; In the below-…

最小堆實現代碼

參考算法導論、數據結構相關書籍&#xff0c;寫得最小堆實現的源代碼如下&#xff1a; 1 //2 //--最小堆實例3 //4 5 #include <iostream>6 #include <vector>7 #include <string>8 using namespace std;9 10 template<typename Comparable>11 class m…

非常好的在網頁中顯示pdf的方法

今天有一需求&#xff0c;要在網頁中顯示pdf&#xff0c;于是立馬開始搜索解決方案&#xff0c;無意中發現一個非常好的解決方法&#xff0c;詳見http://blogs.adobe.com/pdfdevjunkie/web_designers_guide。 其實就光看這個網站也足夠了&#xff0c;http://www.pdfobject.com/…