socket网络传输及总结(一)

(0)
1.          对于普通的传输字符串,用 BufferedInputStream /BufferedOutputStream os.println(), is.readline() 即可。
2.          对于文件的传输,用 FileInputStream /FileOutputStream DataInputStream /DataOutputStream os.write(), is.read() 即可。
3.          对于对象的传输,用 ObjectInputStream /ObjectOutputStream os.writeObject(), is.readObject() 即可 .
4.          socket 的消息头,一般包括命令码,序号号,消息长度,错误码(状态码)。其消息的格式,要与通讯的对方约定好消息的格式。
5.          socket 远程调用外部的方法:实际就是通过发送一个命令码,对方接受到命令码后,根据双方统一的命令码,适配相应的对象及方法,对对象进行实例化,且调用此对象的相应方法。
6.          设置 socket 的通讯超时机制。
7.          设置 socket 的安全通讯机制。
 
 
(1)
简单实现文件在网络中的传输,要实现高级功能,在此基础上进行修改即可。
分2个类实现,FileSender负责文件发送,FileIncepter负责文件接受:
 
用socket传输文件本质: 发送端:打开文件,将文件中字符串发给接收端;接收端接收字符串,写入文件中即可。
 
writeLong(long)
将一 long 作为八字节值,写入该基本输出流,高字节优先。
writeShort(int)
将一 short 作为两字节值,写入该基本输出流,高字节优先。
writeUTF(String)
使用独立于机器的 UTF-8 编码格式,将一个串写入该基本输出流。
 
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class FileSender {

   private ServerSocket ss = null;

   public FileSender() {

  }

   public void startSend(String filePath, int port) {
     // socket输出流
    DataOutputStream os = null;
     // 文件输入流
    DataInputStream is = null;
     // 建立socket连接
    Socket socket = null;
     try {
       // 选择进行传输的文件
      File file = new File(filePath);

       // 建立socket监听
      ss = new ServerSocket(port);

      socket = ss.accept();

      os = new DataOutputStream(socket.getOutputStream());

       // 将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,
       // 具体可以参见Think In Java 4th里有现成的代码。
      os.writeUTF(file.getName());
      os.flush();
      os.writeLong(( long) file.length());
      os.flush();

      is = new DataInputStream( new BufferedInputStream(
           new FileInputStream(filePath)));
       // 缓冲区大小
       int bufferSize = 8192;
       // 缓冲区
       byte[] buf = new byte[bufferSize];
       // 传输文件
       while ( true) {
         int read = 0;
         if (is != null) {
          read = is.read(buf);
        }

         if (read == -1) {
           break;
        }
        os.write(buf, 0, read);
      }
      os.flush();

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
       // 关闭所有连接
       try {
         if (os != null)
          os.close();
      } catch (IOException e) {
      }
       try {
         if (is != null)
          is.close();
      } catch (IOException e) {
      }
       try {
         if (socket != null)
          socket.close();
      } catch (IOException e) {
      }
       try {
         if (ss != null)
          ss.close();
      } catch (IOException e) {
      }
    }

  }

   public static void main(String[] args) {
     new FileSender().startSend( "E:\\JDK_API_1_6_zh_CN.CHM", 8821);
  }
}


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class FileIncepter {

   public FileIncepter() {

  }

   public void getFile(String savePath, String ip, int port) {
     // 建立socket连接
    Socket socket = null;
     try {
      socket = new Socket(ip, port);
    } catch (UnknownHostException e1) {
      e1.printStackTrace();
    } catch (IOException e1) {
      e1.printStackTrace();
    }
     // 建立socket输入流
    DataInputStream inputStream = null;
     try {
      inputStream = new DataInputStream( new BufferedInputStream(socket
          .getInputStream()));
    } catch (IOException e1) {
      e1.printStackTrace();
    }
     try {
       // 缓冲区大小
       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 + "    KB");
      System.out.println( "开始接收文件!");

       // 获取文件
       while ( true) {
         int read = 0;
         if (inputStream != null) {
          read = inputStream.read(buf);
        }
        passedlen += read;
         if (read == -1) {
           break;
        }
        System.out.println( "文件接收了" + (passedlen * 100 / len) + "%");
        fileOut.write(buf, 0, read);
      }
      System.out.println( "接收完成,文件存为" + savePath);
      fileOut.close();
    } catch (Exception e) {
      e.printStackTrace();
       return;
    }
  }

   public static void main(String[] args) {
     new FileIncepter().getFile( "F:\\", "localhost", 8821);
  }
}
 
(2)
socket传递Object对象:
要传递的对象:
public class Employee implements Serializable {            
        
             private int employeeNumber;            
             private String employeeName;            
        
             Employee( int num, String name) {            
                    employeeNumber = num;            
                    employeeName= name;            
             }            
        
                 public int getEmployeeNumber() {            
                     return employeeNumber ;            
             }            
        
             public void setEmployeeNumber( int num) {            
                    employeeNumber = num;            
             }            
        
             public String getEmployeeName() {            
                     return employeeName ;            
             }            
        
             public void setEmployeeName(String name) {            
                    employeeName = name;            
             }            
        }      
 
 
  
client:
public class Client {        
         public static void main(String[] arg) {        
                 try {        
                        Employee joe = new Employee(150, "Joe");        
                        System.out.println( "employeeNumber= " + joe.getEmployeeNumber());        
                        System.out.println( "employeeName= " + joe.getEmployeeName());        
                        Socket socketConnection = new Socket( "127.0.0.1", 11111);        
                        ObjectOutputStream clientOutputStream = new ObjectOutputStream(        
                                        socketConnection.getOutputStream());        
                        ObjectInputStream clientInputStream = new ObjectInputStream(        
                                        socketConnection.getInputStream());        
                        clientOutputStream.writeObject(joe);        
                        joe = (Employee) clientInputStream.readObject();        
                        System.out.println( "employeeNumber= " + joe.getEmployeeNumber());        
                        System.out.println( "employeeName= " + joe.getEmployeeName());        
                        clientOutputStream.close();        
                        clientInputStream.close();        
                } catch (Exception e) {        
                        System.out.println(e);        
                }        
        }        
}        
 
 

server端:
java 代码
public class Server {        
         public static void main(String[] arg) {        
                Employee employee = null;        
                 try {        
                        ServerSocket socketConnection = new ServerSocket(11111);        
                        System.out.println( "Server Waiting");        
                        Socket pipe = socketConnection.accept();        
                        ObjectInputStream serverInputStream = new ObjectInputStream(pipe        
                                        .getInputStream());        
                        ObjectOutputStream serverOutputStream = new ObjectOutputStream(pipe        
                                        .getOutputStream());        
                        employee = (Employee) serverInputStream.readObject();        
                        employee.setEmployeeNumber(256);        
                        employee.setEmployeeName( "li");        
                        serverOutputStream.writeObject(employee);        
                        serverInputStream.close();        
                        serverOutputStream.close();        
                } catch (Exception e) {        
                        System.out.println(e);        
                }        
        }        
}        
 
 
 

你可能感兴趣的:(socket,职场,休闲,网络传输)