精华内容
下载资源
问答
  • socket传文件

    2014-12-10 15:35:03
    socket,安卓客户端向pc服务器端传文件。 安卓客户端代码: package com.example.androidclient2; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io....

    用socket,安卓客户端向pc服务器端传文件。

    一开始传出的文件有多出来的字节,后来通过局部修改后没有任何问题了。

    安卓客户端代码:

    package com.example.androidclient2;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import android.os.Bundle;
    import android.app.Activity;
    
    /**
     * 对传文件客户端的测试
     * @author nm 2014-12-10
     */
    public class ClientActivity extends Activity {
    	private Socket socket;
    	private OutputStream streamOut;
    	private InputStream streamIn;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		socketPhone();
    	}
    
    	private void socketPhone() {
    		new Thread(){
    			@Override
    			public void run() {
    				super.run();
    				try {
    					socket = new Socket("192.168.0.90", 10000);
    					streamIn = socket.getInputStream();
    					streamOut = socket.getOutputStream();
    					interaction();
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		}.start();
    	}
    
    	private void interaction() {
    		new Thread() {
    			@Override
    			public void run() {
    				super.run();
    				try {
    					while (true) {
    						String path = "/mnt/sdcard/abc.mp3";
    						FileInputStream fileIn = new FileInputStream(path);
    						
    						// 这个循环有限发送
    						int a = 0,b = 0;
    						while (a != -1) {
    							byte[] fileByte = new byte[1024];
    							a = (fileIn.read(fileByte, 0, 1024));
    							b += a;
    							System.out.println("a==================" + a+  " ,b="+b);
    							if(a > 0){
    								System.out.println("a---------------------------------" + a);
    								streamOut.write(fileByte, 0, a);
    								streamOut.flush();
    							}
    						}
    						fileIn.close();
    						break;
    					}
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}.start();
    	}
    }
    pc服务器端的代码如下:

    import java.io.FileOutputStream;
    import java.io.IOException;  
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;  
    import java.net.Socket;  
      
    public class MyServer {  
    	private static ServerSocket server;
    	private static Socket socket;
    	private static OutputStream streamOut;
    	private static InputStream streamIn;
    	
        public static void main(String[] args) throws IOException {
            server = new ServerSocket(10000);
            acceptClient();
        }
        
        private static void acceptClient() throws IOException {
            new Thread(new Runnable() {  
                public void run() { 
                	while (true) {
    	                try {
    	                	socket = server.accept();  //Socket[addr=/192.168.0.90,port=53418,localport=10000]
    	                	streamIn = socket.getInputStream();
    	            		streamOut = socket.getOutputStream();
    	            		invoke();
    	                } catch(Exception ex) {  
    	                    ex.printStackTrace();  
    	                }
                	}
                }  
            }).start();  
        }
    
        private static FileOutputStream file;
    	private static String savePath = "E:/test/nmsong.mp3";
    	protected static void invoke() {
    		new Thread(){
    			@Override
    			public void run() {
    				super.run();
    				try {
    					int index =0;
    					file = new FileOutputStream(savePath, false);
    					while(true){
    						int size = streamIn.available();
    						index++;
    						//下面先放到文件里面试试能不能成功,结果不能成功。
    						byte[] buffer = new byte[1024];
    						int buffer1 = streamIn.read(buffer);
    						System.out.println("index = "+index + " size=" + size + ", buffer1=" + buffer1);
    						file.write(buffer, 0 ,buffer1);//后面的两个参数是必须的,否则字节不足默认bugger的长度,则补0。
    					}
    				} catch (Exception e) {
    					e.printStackTrace();
    					return;
    				}
    			}
    		}.start();
    	}
    }
    完。

    展开全文
  • socket 传文件

    2015-08-21 11:21:00
    package com.example.testpicture; import java.io.DataInputStream; import java.io.FileOutputStream; import java.net.InetAddress; import java.net.ServerSocket;...import java.net.Socket; import ja
    package com.example.testpicture;


    import java.io.DataInputStream;
    import java.io.FileOutputStream;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;


    public class PictureAcceptThread extends Thread {


    private int port = 8086;
    private String path;
    boolean isExit;


    public PictureAcceptThread(String path) {
    this.path = path;
    }


    public void startProcess() {
    Socket s = null;
    try {
    ServerSocket ss = new ServerSocket(port);
    String savaPath = path;
    // 选择进行传输的文件
    while (!isInterrupted()) {
    s = ss.accept();
    int bufferSize = 8192;
    byte[] buf = new byte[bufferSize];
    int passedlen = 0;
    long len = 0;
    DataInputStream dis = new DataInputStream(s.getInputStream());
    path += dis.readUTF();
    len = dis.readLong();
    FileOutputStream os = new FileOutputStream(path);
    int read = 0;
    while (!isExit && (read = dis.read(buf)) != -1) {
    os.write(buf, 0, read);
    }
    os.close();
    dis.close();
    s.close();
    }
    ss.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }


    public void stopProcess() {
    this.interrupt();
    }


    public void run() {
    startProcess();
    }


    public static void main(String[] args) {


    }


    }


    package com.example.testpicture;


    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;


    public class PictureSendThread extends Thread {
    private String ip;
    private int port;
    private Socket client;
    private String filePath;
    private boolean isExit;


    public PictureSendThread(String ip, int port, String filePath) {
    this.ip = ip;
    this.port = port;
    this.filePath = filePath;
    }


    public void startProcess() {
    try {
    client = new Socket(ip, port);
    DataOutputStream mOutput = new DataOutputStream(
    client.getOutputStream());
    File fi = new File(filePath);
    mOutput.writeUTF(fi.getName());
    mOutput.flush();
    mOutput.writeLong((long) fi.length());
    mOutput.flush();


    FileInputStream fin = new FileInputStream(filePath);
    int bufferSize = 8192;
    byte[] buf = new byte[bufferSize];
    int read = 0;
    while (!isExit && (read = fin.read(buf)) != -1) {
    mOutput.write(buf, 0, read);
    }
    mOutput.flush();
    fin.close();
    mOutput.close();
    client.close();
    } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }


    public void run() {
    startProcess();
    }


    }

    展开全文
  • android socket传文件

    2017-07-25 11:51:21
    android socket 传文件,自动配置s端ip
  • Socket传文件

    千次阅读 2008-03-30 19:07:00
    导读: 非常简单的一个传文件的功能;为多个客户端每天定时分配资料,Timer没有加进去,参考参考! 服务端: package cn.jatula.socket; import java.io.BufferedInputStream; import java.io.DataInputStream; ...
    
    	导读: 
      非常简单的一个传文件的功能;为多个客户端每天定时分配资料,Timer没有加进去,参考参考!
      服务端:
      
      package cn.jatula.socket;
      import java.io.BufferedInputStream;
      import java.io.DataInputStream;
      import java.io.DataOutputStream;
      import java.io.File;
      import java.io.FileInputStream;
      import java.net.ServerSocket;
      import java.net.Socket;
      /**
      * 服务器端
      * @author lake
      *
      */
      public class ServerTest {
      int port = 8821;
      void start() {
      Socket s = null;
      try {
      ServerSocket ss = new ServerSocket(port);
      while (true) {
      // 选择进行传输的文件
      String filePath = "C://jatula.rar";
      File fi = new File(filePath);
      System.out.println("文件长度:" + (int) fi.length());
      // public Socket accept() throws
      // IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。
      s = ss.accept();
      System.out.println("建立socket链接");
      DataInputStream dis = new DataInputStream(
      new BufferedInputStream(s.getInputStream()));
      dis.readByte();
      DataInputStream fis = new DataInputStream(
      new BufferedInputStream(new FileInputStream(filePath)));
      DataOutputStream ps = new DataOutputStream(s.getOutputStream());
      //将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工。
      ps.writeUTF(fi.getName());
      ps.flush();
      ps.writeLong((long) fi.length());
      ps.flush();
      int bufferSize = 8192;
      byte[] buf = new byte[bufferSize];
      while (true) {
      int read = 0;
      if (fis != null) {
      read = fis.read(buf);
      }
      if (read == -1) {
      break;
      }
      ps.write(buf, 0, read);
      }
      ps.flush();
      // 注意关闭socket链接哦,不然客户端会等待server的数据过来,
      // 直到socket超时,导致数据不完整。
      fis.close();
      s.close();
      System.out.println("文件传输完成");
      }
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      public static void main(String arg[]) {
      new ServerTest().start();
      }
      }
      
      
      客户端:
      
      package cn.jatula.socket;
      import java.io.BufferedOutputStream;
      import java.io.DataInputStream;
      import java.io.DataOutputStream;
      import java.io.FileOutputStream;
      /**
      * 客户端
      * @author lake
      *
      */
      public class ClientTest {
      private ClientSocket cs = null;
      private String ip = "localhost";// 设置成服务器IP
      private int port = 8821;
      private String sendMessage = "Windwos";
      public ClientTest() {
      try {
      if (createConnection()) {
      sendMessage();
      getMessage();
      }
      } catch (Exception ex) {
      ex.printStackTrace();
      }
      }
      private boolean createConnection() {
      cs = new ClientSocket(ip, port);
      try {
      cs.CreateConnection();
      System.out.print("连接服务器成功!" + "/n");
      return true;
      } catch (Exception e) {
      System.out.print("连接服务器失败!" + "/n");
      return false;
      }
      }
      private void sendMessage() {
      if (cs == null)
      return;
      try {
      cs.sendMessage(sendMessage);
      } catch (Exception e) {
      System.out.print("发送消息失败!" + "/n");
      }
      }
      private void getMessage() {
      if (cs == null)
      return;
      DataInputStream inputStream = null;
      try {
      inputStream = cs.getMessageStream();
      } catch (Exception e) {
      System.out.print("接收消息缓存错误/n");
      return;
      }
      try {
      // 本地保存路径,文件名会自动从服务器端继承而来。
      String savePath = "E://";
      int bufferSize = 8192;
      byte[] buf = new byte[bufferSize];
      int passedlen = 0;
      long len = 0;
      savePath += inputStream.readUTF();
      DataOutputStream fileOut = new DataOutputStream(
      new BufferedOutputStream(new BufferedOutputStream(
      new FileOutputStream(savePath))));
      len = inputStream.readLong();
      System.out.println("文件的长度为:" + len + "/n");
      System.out.println("开始接收文件!" + "/n");
      while (true) {
      int read = 0;
      if (inputStream != null) {
      read = inputStream.read(buf);
      }
      passedlen += read;
      if (read == -1) {
      break;
      }
      // 下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比
      System.out.println("文件接收了" + (passedlen * 100 / len) + "%/n");
      fileOut.write(buf, 0, read);
      }
      System.out.println("接收完成,文件存为" + savePath + "/n");
      fileOut.close();
      } catch (Exception e) {
      System.out.println("接收消息错误" + "/n");
      return;
      }
      }
      public static void main(String arg[]) {
      new ClientTest();
      }
      }
      
      辅助类
      
      package cn.jatula.socket;
      import java.net.*;
      import java.io.*;
      /**
      * socket的Util辅助类
      * @author lake
      *
      */
      public class ClientSocket {
      private String ip;
      private int port;
      private Socket socket = null;
      DataOutputStream out = null;
      DataInputStream getMessageStream = null;
      public ClientSocket(String ip, int port) {
      this.ip = ip;
      this.port = port;
      }
      /** */
      /**
      * 创建socket连接
      *
      * @throws Exception
      * exception
      */
      public void CreateConnection() throws Exception {
      try {
      socket = new Socket(ip, port);
      } catch (Exception e) {
      e.printStackTrace();
      if (socket != null)
      socket.close();
      throw e;
      } finally {
      }
      }
      public void sendMessage(String sendMessage) throws Exception {
      try {
      out = new DataOutputStream(socket.getOutputStream());
      if (sendMessage.equals("Windows")) {
      out.writeByte(0x1);
      out.flush();
      return;
      }
      if (sendMessage.equals("Unix")) {
      out.writeByte(0x2);
      out.flush();
      return;
      }
      if (sendMessage.equals("Linux")) {
      out.writeByte(0x3);
      out.flush();
      } else {
      out.writeUTF(sendMessage);
      out.flush();
      }
      } catch (Exception e) {
      e.printStackTrace();
      if (out != null)
      out.close();
      throw e;
      } finally {
      }
      }
      public DataInputStream getMessageStream() throws Exception {
      try {
      getMessageStream = new DataInputStream(new BufferedInputStream(
      socket.getInputStream()));
      return getMessageStream;
      } catch (Exception e) {
      e.printStackTrace();
      if (getMessageStream != null)
      getMessageStream.close();
      throw e;
      } finally {
      }
      }
      public void shutDownConnection() {
      try {
      if (out != null)
      out.close();
      if (getMessageStream != null)
      getMessageStream.close();
      if (socket != null)
      socket.close();
      } catch (Exception e) {
      }
      }
      }

    本文转自
    http://jatula.javaeye.com/blog/172815
    展开全文
  • socket传文件

    千次阅读 2008-11-06 22:05:00
    private string path = "F://SmartMovie.EXE"; //要发送的文件 private Socket s; private void listen() { 
    1.        private string path = "F://SmartMovie.EXE";    //要发送的文件
    2.                       private Socket s;                              
    3.          private void listen()
    4.         {
    5.             string ip = "127.0.0.1";   //远程IP 这里定义为自己的机器
    6.             IPAddress[] ih = Dns.GetHostAddresses(ip);       //获得IP列表
    7.             IPAddress newip = ih[0];      //获取IP地址            
    8.             int port = 6789;              //定义端口
    9.             IPEndPoint Conncet = new IPEndPoint(newip, port);     //构造结点
    10.             s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,  ProtocolType.Tcp);                   //初始化socket 
    11.      try
    12.         {                                  
    13.             s.Connect(Conncet);      //连接远程服务器
    14.             if (s.Connected)         //如果连接成功 s.Connected 则为true 否则为 false
    15.             {
    16.                 Console.WriteLine("连接成功");
    17.                 Thread t = new Thread(new ThreadStart(set)); //创建进程
    18.                 t.Start();                             //开始进程
    19.                 Console.WriteLine("发送完毕")      
    20.             }
    21.                }
    22.                 catch(NullReferenceException e)
    23.             {
    24.               Console.WriteLine("{0}",e);
    25.             }
    26.             private void set()                       //创建set函数
    27.         {
    28.             Console.WriteLine("开始发送数据");
    29.             byte[] b = new byte[10000000];            //创建文件缓冲区,这里可以认为文件的最大值
    30.             FileStream file = File.Open(path, FileMode.Open,FileAccess.Read);   //创建文件流
    31.             int start = 0;
    32.             int end = (int)file.Length;               //获取文件长度文件传送如果有需要超过int的范围估计就要改写FileStream类了
    33.       try
    34.           {
    35.             while (end != 0)
    36.             {
    37.                 int count = file.Read(b, start, end);      //把数据写进流
    38.                 start += count;
    39.                 end -= count;
    40.             }
    41.             while (start != 0)
    42.             {
    43.                 int n = s.Send(b, end, start, SocketFlags.None);  //用Socket的Send方法发送流
    44.                 end += n;
    45.                 start -= n;
    46.             }
    47.         
    48.             file.Close();     //关闭文件流
    49.             s.Close();        //关闭Socket
    50.           }  
    51.       catch (NullReferenceException e)
    52.             {
    53.                 Console.WriteLine("{0}", e);
    54.             }             
    55.         }   
    56. 这样文件发送的模型就实现了
    57.     接下去实现文件的接收,首先要确定对方发送文件的长度,其实上面的那段还要加入发送文件长度的功能,实现很简单,就是发送int变量end ,然后要求接收代码返回一个Boolean确定是否发送,这里为了更简明的说清楚原理并没有实现
    58.              private void get()
    59.         {
    60.             string path = "G://da.exe";  //接收的文件
    61.             FileStream file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); //写入文件流
    62.             TcpListener listen = new TcpListener(6789);  //监听端口
    63.             Socket s1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  //定义Socket并初始化
    64.             try
    65.             {
    66.              listen.Start();        //开始监听
    67.             s1 = listen.AcceptSocket();            //获取Socket连接
    68.             byte[] data = new byte[10000000];      //定义缓冲区
    69.             int longer = data.Length;               
    70.             int start = 0;                 
    71.             int mid = 0;
    72.             if (s1.Connected)             //确定连接
    73.             {
    74.                 Console.WriteLine("连接成功");
    75.                 int count = s1.Receive(data, start, longer, SocketFlags.None);  //把接收到的byte存入缓冲区
    76.                 mid += count;
    77.                 longer -= mid;
    78.                 while (count != 0)
    79.                 {
    80.                     count = s1.Receive(data, mid, longer, SocketFlags.None);
    81.                     mid += count;
    82.                     longer -= mid;
    83.                 }
    84.                 file.Write(data, 0, 1214134); //写入文件,1214134为文件大小,可以用socket发送获得,代码前面已经说明。
    85.                 s1.Close();
    86.                 file.Close();
    87.             }
    88.             }
    89.                 catch(NullReferenceException e)
    90.             {
    91.                     Console.WriteLine("{0}",e);
    92.             }
    93.           }
     
    展开全文
  • Java socket 传文件

    2013-01-04 20:15:08
    Java socket 传文件 进度条 多线程 有进度条
  • socket传文件例子.txt

    2012-11-14 22:03:28
    socket传文件例子
  • VC6.0 MFC socket传文件代码VC6.0 MFC socket传文件代码
  • 展开全部客户端代码如下:importjava.io.DataOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.net.InetSocketAddress;.../***文件发送客户端主程序*@aut...
  • /usr/bin/env python# -*-coding:utf-8 -*-import socket, struct, jsondownload_dir = r'D:\Python\python_learning\gd\code\part3\02网络编程\文件传输\client\download'gd_client=socket.socket(socket.AF_...
  • 实现了Socket传输文件,由客户端发送给服务端,文件可以是任何形式,可以参考学习。
  • /usr/bin/envpython#-*-coding:utf-8-*-importsocket,struct,jsondownload_dir=r'D:\Python\python_learning\gd\code\part3\02网络编程\文件传输\client\download'gd_client=socket.socket(socke...
  • (转)socket传文件

    2015-07-23 12:11:54
    socket传文件  private string path = "F:\\SmartMovie.EXE"; //要发送的文件  private Socket s;   private void listen()  {
  • java socket传文件,客户端将文件读取到byte[]中,然后用Map对相关内容进行包装之后输出到服务器端,但服务器端读取文件内容的循环除第一次读取的Map是客户端写入过来的内容外,从第二次循环开始Map的内容都跟第一次...
  • Socket socket = null; DataOutputStream dout = null; File file = new File("D:\\1.jpg");//要读取的文件的路径 FileInputStream fin = null; byte[] inByte = new byte[1024]; int length = 0; try { server = ...
  • /usr/bin/env python# -*-coding:utf-8 -*-import socket, struct, jsondownload_dir = r'D:\Python\python_learning\gd\code\part3\02网络编程\文件传输\client\download'gd_client=socket.socket(socket.AF_...
  • C# Socket传文件

    2009-10-08 21:53:54
    利用C#Socket进行文件传输,进行了有效的封装。
  • 客户端# -*- coding: utf-8 -*-import socketimport argparseimport osimport hashlibimport pickledef parse_args():parser = argparse.ArgumentParser()parser.add_argument("-f","--file",help="the file you ...
  • 1、Socket传文件2、多线程3、paramiko1、Socket传文件Socket服务端 catserver.py #!/usr/bin/envpython #coding:utf-8 importSocketServer importos classMyServer(SocketServer.BaseRequestHandler):...
  • 本篇文章主要介绍了python:socket传输大文件示例,具有一定的参考价值,有兴趣的可以了解一下,文件可以传输,但是对比传输前后的文件socket_test.txt,末尾有一些不一致服务端代码:#!/usr/bin/python# -*- ...
  • python socket传文件

    万次阅读 2015-07-24 15:39:30
    python传输文件最重要的有两步: 1).将要传输的文件的信息发送过去,包括文件包,大小以及其它信息; 2).发送端读取文件内容并发送过去,...from socket import * import os import struct ADDR = ('192.1
  • python socket传文件

    2015-07-24 15:39:30
    python传输文件最重要的有两步: 1).将要传输的文件的信息发送过去,包括文件包,大小以及其它信息; 2).发送端读取文件内容并发送过去,接受端将缓存里面的内容写入文件. 发送端: ...from socket impor...
  • 以前没有试过这样的操作,思考了一下,因为有串口转wifi的模块,所以决定上位机用python来写一个socket实现这个功能(由于下位机是stm32,所以下位机的发送就只能用c来写了)。尝试先用python写一个demo来测试下是否...
  • 利用socket传文件

    2015-05-04 15:38:00
    欢迎批评 也可以看看这里的比较详细http://www.jb51.net/article/53733.htm 服务端#include <stdio.h> #include <string.h>...sys/socket.h> #include <arpa/inet....
  • java socket传文件

    2016-04-13 21:13:07
    socket传文件,如果不关流,服务器就会一直等着,文件也是空的,但是我文件传完了之后还需要OutputStream写东西给服务器交互,怎么办?

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,493
精华内容 597
关键字:

socket传文件