溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java Socket實現(xiàn)的傳輸對象功能示例

發(fā)布時間:2020-10-06 16:42:33 來源:腳本之家 閱讀:229 作者:kongxx 欄目:編程語言

本文實例講述了Java Socket實現(xiàn)的傳輸對象功能。分享給大家供大家參考,具體如下:

前面兩篇文章介紹了怎樣建立Java Socket通信,這里說一下怎樣使用Java Socket來傳輸對象。

首先需要一個普通的對象類,由于需要序列化這個對象以便在網絡上傳輸,所以實現(xiàn)java.io.Serializable接口就是必不可少的了,如下:

package com.googlecode.garbagecan.test.socket.sample3;
public class User implements java.io.Serializable {
  private static final long serialVersionUID = 1L;
  private String name;
  private String password;
  public User() {
  }
  public User(String name, String password) {
    this.name = name;
    this.password = password;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
}

對于Server端的代碼,代碼中分別使用了ObjectInputStream和ObjectOutputStream來接收和發(fā)送socket中的InputStream和OutputStream,然后轉換成Java對象,如下:

package com.googlecode.garbagecan.test.socket.sample3;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyServer {
  private final static Logger logger = Logger.getLogger(MyServer.class.getName());
  public static void main(String[] args) throws IOException {
    ServerSocket server = new ServerSocket(10000);
    while (true) {
      Socket socket = server.accept();
      invoke(socket);
    }
  }
  private static void invoke(final Socket socket) throws IOException {
    new Thread(new Runnable() {
      public void run() {
        ObjectInputStream is = null;
        ObjectOutputStream os = null;
        try {
          is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
          os = new ObjectOutputStream(socket.getOutputStream());
          Object obj = is.readObject();
          User user = (User)obj;
          System.out.println("user: " + user.getName() + "/" + user.getPassword());
          user.setName(user.getName() + "_new");
          user.setPassword(user.getPassword() + "_new");
          os.writeObject(user);
          os.flush();
        } catch (IOException ex) {
          logger.log(Level.SEVERE, null, ex);
        } catch(ClassNotFoundException ex) {
          logger.log(Level.SEVERE, null, ex);
        } finally {
          try {
            is.close();
          } catch(Exception ex) {}
          try {
            os.close();
          } catch(Exception ex) {}
          try {
            socket.close();
          } catch(Exception ex) {}
        }
      }
    }).start();
  }
}

Client也和Server端類似,同樣使用ObjectOutputStream和ObjectInputStream來處理,如下:

package com.googlecode.garbagecan.test.socket.sample3;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyClient {
  private final static Logger logger = Logger.getLogger(MyClient.class.getName());
  public static void main(String[] args) throws Exception {
    for (int i = 0; i < 100; i++) {
      Socket socket = null;
      ObjectOutputStream os = null;
      ObjectInputStream is = null;
      try {
        socket = new Socket("localhost", 10000);
        os = new ObjectOutputStream(socket.getOutputStream());
        User user = new User("user_" + i, "password_" + i);
        os.writeObject(user);
        os.flush();
        is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
        Object obj = is.readObject();
        if (obj != null) {
          user = (User)obj;
          System.out.println("user: " + user.getName() + "/" + user.getPassword());
        }
      } catch(IOException ex) {
        logger.log(Level.SEVERE, null, ex);
      } finally {
        try {
          is.close();
        } catch(Exception ex) {}
        try {
          os.close();
        } catch(Exception ex) {}
        try {
          socket.close();
        } catch(Exception ex) {}
      }
    }
  }
}

最后測試上面的代碼,首先運行Server類,然后運行Client類,就可以分別在Server端和Client端控制臺看到接收到的User對象實例了。

更多關于java相關內容感興趣的讀者可查看本站專題:《Java Socket編程技巧總結》、《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》和《Java緩存操作技巧匯總》

希望本文所述對大家java程序設計有所幫助。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI