温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java Socket实现的传输对象功能示例

发布时间:2020-10-06 16:42:33 来源:脚本之家 阅读:230 作者:kongxx 栏目:编程语言

本文实例讲述了Java Socket实现的传输对象功能。分享给大家供大家参考,具体如下:

前面两篇文章介绍了怎样建立Java Socket通信,这里说一下怎样使用Java Socket来传输对象。

首先需要一个普通的对象类,由于需要序列化这个对象以便在网络上传输,所以实现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来接收和发送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数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI