• java socket


    引用:http://wiseideal.iteye.com/blog/1167886

    Java代码  收藏代码
    1. package sterning;  
    2.   
    3. import java.io.BufferedInputStream;  
    4. import java.io.DataInputStream;  
    5. import java.io.DataOutputStream;  
    6. import java.io.File;  
    7. import java.io.FileInputStream;  
    8. import java.net.ServerSocket;  
    9. import java.net.Socket;  
    10.   
    11. public class ServerTest {  
    12.     int port = 8821;  
    13.   
    14.     void start() {  
    15.         Socket s = null;  
    16.         try {  
    17.             ServerSocket ss = new ServerSocket(port);  
    18.             while (true) {  
    19.                 // 选择进行传输的文件  
    20.                 String filePath = "D:\\lib.rar";  
    21.                 File fi = new File(filePath);  
    22.   
    23.                 System.out.println("文件长度:" + (int) fi.length());  
    24.   
    25.                 // public Socket accept() throws  
    26.                 // IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。  
    27.   
    28.                 s = ss.accept();  
    29.                 System.out.println("建立socket链接");  
    30.                 DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));  
    31.                 dis.readByte();  
    32.   
    33.                 DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));  
    34.                 DataOutputStream ps = new DataOutputStream(s.getOutputStream());  
    35.                 //将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。  
    36.                 ps.writeUTF(fi.getName());  
    37.                 ps.flush();  
    38.                 ps.writeLong((long) fi.length());  
    39.                 ps.flush();  
    40.   
    41.                 int bufferSize = 8192;  
    42.                 byte[] buf = new byte[bufferSize];  
    43.   
    44.                 while (true) {  
    45.                     int read = 0;  
    46.                     if (fis != null) {  
    47.                         read = fis.read(buf);  
    48.                     }  
    49.   
    50.                     if (read == -1) {  
    51.                         break;  
    52.                     }  
    53.                     ps.write(buf, 0, read);  
    54.                 }  
    55.                 ps.flush();  
    56.                 // 注意关闭socket链接哦,不然客户端会等待server的数据过来,  
    57.                 // 直到socket超时,导致数据不完整。                  
    58.                 fis.close();  
    59.                 s.close();                  
    60.                 System.out.println("文件传输完成");  
    61.             }  
    62.   
    63.         } catch (Exception e) {  
    64.             e.printStackTrace();  
    65.         }  
    66.     }  
    67.   
    68.     public static void main(String arg[]) {  
    69.         new ServerTest().start();  
    70.     }  
    71. }  



    2.socket的Util辅助类 

    Java代码  收藏代码
    1. package sterning;  
    2.   
    3. import java.net.*;  
    4. import java.io.*;  
    5.   
    6. public class ClientSocket {  
    7.     private String ip;  
    8.   
    9.     private int port;  
    10.   
    11.     private Socket socket = null;  
    12.   
    13.     DataOutputStream out = null;  
    14.   
    15.     DataInputStream getMessageStream = null;  
    16.   
    17.     public ClientSocket(String ip, int port) {  
    18.         this.ip = ip;  
    19.         this.port = port;  
    20.     }  
    21.   
    22.     /** *//** 
    23.      * 创建socket连接 
    24.      *  
    25.      * @throws Exception 
    26.      *             exception 
    27.      */  
    28.     public void CreateConnection() throws Exception {  
    29.         try {  
    30.             socket = new Socket(ip, port);  
    31.         } catch (Exception e) {  
    32.             e.printStackTrace();  
    33.             if (socket != null)  
    34.                 socket.close();  
    35.             throw e;  
    36.         } finally {  
    37.         }  
    38.     }  
    39.   
    40.     public void sendMessage(String sendMessage) throws Exception {  
    41.         try {  
    42.             out = new DataOutputStream(socket.getOutputStream());  
    43.             if (sendMessage.equals("Windows")) {  
    44.                 out.writeByte(0x1);  
    45.                 out.flush();  
    46.                 return;  
    47.             }  
    48.             if (sendMessage.equals("Unix")) {  
    49.                 out.writeByte(0x2);  
    50.                 out.flush();  
    51.                 return;  
    52.             }  
    53.             if (sendMessage.equals("Linux")) {  
    54.                 out.writeByte(0x3);  
    55.                 out.flush();  
    56.             } else {  
    57.                 out.writeUTF(sendMessage);  
    58.                 out.flush();  
    59.             }  
    60.         } catch (Exception e) {  
    61.             e.printStackTrace();  
    62.             if (out != null)  
    63.                 out.close();  
    64.             throw e;  
    65.         } finally {  
    66.         }  
    67.     }  
    68.   
    69.     public DataInputStream getMessageStream() throws Exception {  
    70.         try {  
    71.             getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));  
    72.             return getMessageStream;  
    73.         } catch (Exception e) {  
    74.             e.printStackTrace();  
    75.             if (getMessageStream != null)  
    76.                 getMessageStream.close();  
    77.             throw e;  
    78.         } finally {  
    79.         }  
    80.     }  
    81.   
    82.     public void shutDownConnection() {  
    83.         try {  
    84.             if (out != null)  
    85.                 out.close();  
    86.             if (getMessageStream != null)  
    87.                 getMessageStream.close();  
    88.             if (socket != null)  
    89.                 socket.close();  
    90.         } catch (Exception e) {  
    91.   
    92.         }  
    93.     }  
    94. }  



    3.客户端 

    Java代码  收藏代码
    1. package sterning;  
    2.   
    3. import java.io.BufferedOutputStream;  
    4. import java.io.DataInputStream;  
    5. import java.io.DataOutputStream;  
    6. import java.io.FileOutputStream;  
    7.   
    8. public class ClientTest {  
    9.     private ClientSocket cs = null;  
    10.   
    11.     private String ip = "localhost";// 设置成服务器IP  
    12.   
    13.     private int port = 8821;  
    14.   
    15.     private String sendMessage = "Windwos";  
    16.   
    17.     public ClientTest() {  
    18.         try {  
    19.             if (createConnection()) {  
    20.                 sendMessage();  
    21.                 getMessage();  
    22.             }  
    23.   
    24.         } catch (Exception ex) {  
    25.             ex.printStackTrace();  
    26.         }  
    27.     }  
    28.   
    29.     private boolean createConnection() {  
    30.         cs = new ClientSocket(ip, port);  
    31.         try {  
    32.             cs.CreateConnection();  
    33.             System.out.print("连接服务器成功!" + "\n");  
    34.             return true;  
    35.         } catch (Exception e) {  
    36.             System.out.print("连接服务器失败!" + "\n");  
    37.             return false;  
    38.         }  
    39.   
    40.     }  
    41.   
    42.     private void sendMessage() {  
    43.         if (cs == null)  
    44.             return;  
    45.         try {  
    46.             cs.sendMessage(sendMessage);  
    47.         } catch (Exception e) {  
    48.             System.out.print("发送消息失败!" + "\n");  
    49.         }  
    50.     }  
    51.   
    52.     private void getMessage() {  
    53.         if (cs == null)  
    54.             return;  
    55.         DataInputStream inputStream = null;  
    56.         try {  
    57.             inputStream = cs.getMessageStream();  
    58.         } catch (Exception e) {  
    59.             System.out.print("接收消息缓存错误\n");  
    60.             return;  
    61.         }  
    62.   
    63.         try {  
    64.             //本地保存路径,文件名会自动从服务器端继承而来。  
    65.             String savePath = "E:\\";  
    66.             int bufferSize = 8192;  
    67.             byte[] buf = new byte[bufferSize];  
    68.             int passedlen = 0;  
    69.             long len=0;  
    70.               
    71.             savePath += inputStream.readUTF();  
    72.             DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));  
    73.             len = inputStream.readLong();  
    74.               
    75.             System.out.println("文件的长度为:" + len + "\n");  
    76.             System.out.println("开始接收文件!" + "\n");  
    77.                       
    78.             while (true) {  
    79.                 int read = 0;  
    80.                 if (inputStream != null) {  
    81.                     read = inputStream.read(buf);  
    82.                 }  
    83.                 passedlen += read;  
    84.                 if (read == -1) {  
    85.                     break;  
    86.                 }  
    87.                 //下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比  
    88.                 System.out.println("文件接收了" +  (passedlen * 100/ len) + "%\n");  
    89.                 fileOut.write(buf, 0, read);  
    90.             }  
    91.             System.out.println("接收完成,文件存为" + savePath + "\n");  
    92.   
    93.             fileOut.close();  
    94.         } catch (Exception e) {  
    95.             System.out.println("接收消息错误" + "\n");  
    96.             return;  
    97.         }  
    98.     }  
    99.   
    100.     public static void main(String arg[]) {  
    101.         new ClientTest();  
    102.     }  
    103. }  
  • 相关阅读:
    力扣(LeetCode)验证回文串 个人题解(C++)
    力扣(LeetCode)平方数之和 个人题解
    Exclusive Access 2 UVA
    C语言中指针*p[N], (*P)[N]的区别
    2018年蓝桥杯国赛比赛心得
    2018acm/icpc西安邀请赛比赛心得
    [最小割]Cable TV Network UVA
    Tree Reconstruction UVA
    Twenty Questions UVA
    python中的enumerate 函数(编号的实现方式)
  • 原文地址:https://www.cnblogs.com/sode/p/2384494.html
Copyright © 2020-2023  润新知