`
lzkyo
  • 浏览: 458601 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java socket编程收藏之一

阅读更多

(1)Server端

Java代码 复制代码
  1. import java.io.BufferedInputStream;   
  2. import java.io.DataInputStream;   
  3. import java.io.DataOutputStream;   
  4. import java.io.File;   
  5. import java.io.FileInputStream;   
  6. import java.net.ServerSocket;   
  7. import java.net.Socket;   
  8.   
  9. public class Server{   
  10.        
  11.     //ServerSocket监听的端口,等待客户连接请求,客户连接后,会话产生,在完成会话后,关闭连接。   
  12.     int port = 8821;   
  13.   
  14.     void start() {   
  15.         Socket s = null;   
  16.         try {   
  17.             //在连接成功时,应用程序两端都会产生一个Socket实例   
  18.             ServerSocket ss = new ServerSocket(port);   
  19.             while (true) {   
  20.                    
  21.                 String filePath = "D:/bars.jar";   
  22.                 File fi = new File(filePath);   
  23.   
  24.                 //Accept方法用于产生"阻塞",直到接受到一个连接,并且返回一个客户端的Socket对象实例   
  25.                 System.out.println("Ready to accept task!");   
  26.                 s = ss.accept();   
  27.                    
  28.                 //s.getInputStream()获得网络连接输入,同时返回一个IutputStream对象实例   
  29.                 DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));   
  30.                 dis.readByte();   
  31.   
  32.                 DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));   
  33.                 //s.getOutputStream()网络连接输出   
  34.                 DataOutputStream ps = new DataOutputStream(s.getOutputStream());   
  35.                 //将文件名及长度传给客户端。   
  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.                 fis.close();   
  57.                 s.close(); //关闭socket                  
  58.                 System.out.println("Task over!");   
  59.             }   
  60.   
  61.         } catch (Exception e) {   
  62.             e.printStackTrace();   
  63.         }   
  64.     }   
  65.   
  66.     public static void main(String arg[]) {   
  67.         new Server().start();   
  68.     }   
  69. }  
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;

public class Server{
	
	//ServerSocket监听的端口,等待客户连接请求,客户连接后,会话产生,在完成会话后,关闭连接。
    int port = 8821;

    void start() {
        Socket s = null;
        try {
        	//在连接成功时,应用程序两端都会产生一个Socket实例
            ServerSocket ss = new ServerSocket(port);
            while (true) {
            	
                String filePath = "D:/bars.jar";
                File fi = new File(filePath);

                //Accept方法用于产生"阻塞",直到接受到一个连接,并且返回一个客户端的Socket对象实例
                System.out.println("Ready to accept task!");
                s = ss.accept();
                
                //s.getInputStream()获得网络连接输入,同时返回一个IutputStream对象实例
                DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
                dis.readByte();

                DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
                //s.getOutputStream()网络连接输出
                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();
                fis.close();
                s.close(); //关闭socket               
                System.out.println("Task over!");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String arg[]) {
        new Server().start();
    }
}



(2)ClientSocket辅助类

Java代码 复制代码
  1. import java.net.*;   
  2. import java.io.*;   
  3.   
  4. public class ClientSocket {   
  5.     private String ip;   
  6.   
  7.     private int port;   
  8.   
  9.     private Socket socket = null;   
  10.   
  11.     DataOutputStream out = null;   
  12.   
  13.     DataInputStream getMessageStream = null;   
  14.   
  15.     public ClientSocket(String ip, int port) {   
  16.         this.ip = ip;   
  17.         this.port = port;   
  18.     }   
  19.   
  20.     /**  
  21.      * 创建socket连接  
  22.      * @throws Exception  
  23.      */  
  24.     public void CreateConnection() throws Exception {   
  25.         try {   
  26.             socket = new Socket(ip, port);   
  27.         } catch (Exception e) {   
  28.             e.printStackTrace();   
  29.             if (socket != null)   
  30.                 socket.close();   
  31.             throw e;   
  32.         }   
  33.     }   
  34.   
  35.     /**  
  36.      * 往Socket写数据  
  37.      * @param sendMessage  
  38.      * @throws Exception  
  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.             }else {   
  48.                 out.writeUTF(sendMessage);   
  49.                 out.flush();   
  50.             }   
  51.         } catch (Exception e) {   
  52.             e.printStackTrace();   
  53.             if (out != null)   
  54.                 out.close();   
  55.             throw e;   
  56.         }    
  57.     }   
  58.   
  59.     /**  
  60.      * 从Socket读数据  
  61.      * @return  
  62.      * @throws Exception  
  63.      */  
  64.     public DataInputStream getMessageStream() throws Exception {   
  65.         try {   
  66.             getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));   
  67.             return getMessageStream;   
  68.         } catch (Exception e) {   
  69.             e.printStackTrace();   
  70.             if (getMessageStream != null)   
  71.                 getMessageStream.close();   
  72.             throw e;   
  73.         }   
  74.     }   
  75.   
  76.     public void shutDownConnection() {   
  77.         try {   
  78.             if (out != null)   
  79.                 out.close();   
  80.             if (getMessageStream != null)   
  81.                 getMessageStream.close();   
  82.             if (socket != null)   
  83.                 socket.close();   
  84.         } catch (Exception e) {   
  85.   
  86.         }   
  87.     }   
  88. }  
import java.net.*;
import java.io.*;

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
     */
    public void CreateConnection() throws Exception {
        try {
            socket = new Socket(ip, port);
        } catch (Exception e) {
            e.printStackTrace();
            if (socket != null)
                socket.close();
            throw e;
        }
    }

    /**
     * 往Socket写数据
     * @param sendMessage
     * @throws Exception
     */
    public void sendMessage(String sendMessage) throws Exception {
        try {
            out = new DataOutputStream(socket.getOutputStream());
            if (sendMessage.equals("Windows")) {
                out.writeByte(0x1);
                out.flush();
                return;
            }else {
                out.writeUTF(sendMessage);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (out != null)
                out.close();
            throw e;
        } 
    }

    /**
     * 从Socket读数据
     * @return
     * @throws Exception
     */
    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;
        }
    }

    public void shutDownConnection() {
        try {
            if (out != null)
                out.close();
            if (getMessageStream != null)
                getMessageStream.close();
            if (socket != null)
                socket.close();
        } catch (Exception e) {

        }
    }
}



(3)客户端

Java代码 复制代码
  1. import java.io.BufferedOutputStream;   
  2. import java.io.DataInputStream;   
  3. import java.io.DataOutputStream;   
  4. import java.io.FileOutputStream;   
  5.   
  6. public class ClientTest {   
  7.     //Socket对网络上某一个服务器的某一个端口发出连接请求   
  8.     private ClientSocket cs = null;   
  9.   
  10.     private String ip = "localhost";   
  11.   
  12.     private int port = 8821;   
  13.   
  14.     private String sendMessage = "Windwos";   
  15.   
  16.     public ClientTest() {   
  17.         try {   
  18.             if (createConnection()) {   
  19.                 sendMessage();   
  20.                 getMessage();   
  21.             }   
  22.   
  23.         } catch (Exception ex) {   
  24.             ex.printStackTrace();   
  25.         }   
  26.     }   
  27.   
  28.     private boolean createConnection() {   
  29.         cs = new ClientSocket(ip, port);   
  30.         try {   
  31.             cs.CreateConnection();   
  32.             System.out.print("连接服务器成功!" + "\n");   
  33.             return true;   
  34.         } catch (Exception e) {   
  35.             System.out.print("连接服务器失败!" + "\n");   
  36.             return false;   
  37.         }   
  38.   
  39.     }   
  40.   
  41.     private void sendMessage() {   
  42.         if (cs == null)   
  43.             return;   
  44.         try {   
  45.             cs.sendMessage(sendMessage);   
  46.         } catch (Exception e) {   
  47.             System.out.print("发送消息失败!" + "\n");   
  48.         }   
  49.     }   
  50.   
  51.     private void getMessage() {   
  52.         if (cs == null)   
  53.             return;   
  54.         DataInputStream inputStream = null;   
  55.         try {   
  56.             inputStream = cs.getMessageStream();   
  57.         } catch (Exception e) {   
  58.             System.out.print("接收消息缓存错误\n");   
  59.             return;   
  60.         }   
  61.   
  62.         try {   
  63.             //本地保存路径,文件名会自动从服务器端继承而来。   
  64.             String savePath = "E:\\";   
  65.             int bufferSize = 8192;   
  66.             byte[] buf = new byte[bufferSize];   
  67.             int passedlen = 0;   
  68.             long len=0;   
  69.                
  70.             savePath += inputStream.readUTF();   
  71.             DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(savePath)));   
  72.             len = inputStream.readLong();   
  73.                
  74.             System.out.println("文件的长度为:" + len + "\n");   
  75.             System.out.println("开始接收文件!" + "\n");   
  76.                        
  77.             while (true) {   
  78.                 int read = 0;   
  79.                 if (inputStream != null) {   
  80.                     read = inputStream.read(buf);   
  81.                 }   
  82.                 passedlen += read;   
  83.                 if (read == -1) {   
  84.                     break;   
  85.                 }   
  86.                 fileOut.write(buf, 0, read);   
  87.             }   
  88.             System.out.println("接收完成,文件存为" + savePath + "\n");   
  89.   
  90.             fileOut.close();   
  91.         } catch (Exception e) {   
  92.             System.out.println("接收消息错误" + "\n");   
  93.             return;   
  94.         }   
  95.     }   
  96.   
  97.     public static void main(String arg[]) {   
  98.         new ClientTest();   
  99.     }   
  100. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics