基于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.mzph.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/…