美文网首页
Serializable官方实例解析01-对Sockets使用序

Serializable官方实例解析01-对Sockets使用序

作者: Jack魏 | 来源:发表于2022-05-06 22:39 被阅读0次

官方地址:Using Serialization with Sockets

对套接字使用序列化

Serializable官方实例解析01-对Sockets使用序列化

1. 介绍

演示如何使用套接字序列化来发送和接收对象。
在此示例中,当前日期从客户端发送到服务器。文件Client.java提供用于发送日期的代码,文件 Server.java提供用于接收日期的代码。服务器是本地主机。

在阅读源代码之前,每个文件都有一个版权声明,为了节省篇幅,现将翻译如下:

/*
 * Copyright © 2004, 2010 Oracle and/or its affiliates. All  Rights Reserved.
 *  
 * Redistribution and use in source and binary forms, with or 
 * without modification, are permitted provided that the following 
 * conditions are met:
 * 
 * -Redistributions of source code must retain the above copyright  
 *  notice, this list of conditions and the following disclaimer.
 * 
 * -Redistribution in binary form must reproduce the above copyright 
 *  notice, this list of conditions and the following disclaimer in 
 *  the documentation and/or other materials provided with the 
 *  distribution.
 *  
 * Neither the name of Oracle and/or its affiliates. or the names of 
 * contributors may be used to endorse or promote products derived 
 * from this software without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any 
 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND 
 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY 
 * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY 
 * DAMAGES OR LIABILITIES  SUFFERED BY LICENSEE AS A RESULT OF OR 
 * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR 
 * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE 
 * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, 
 * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER 
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF 
 * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *  
 * You acknowledge that Software is not designed, licensed or 
 * intended for use in the design, construction, operation or 
 * maintenance of any nuclear facility. 
 */

版权所有 2004、2010年 Oracle 及其附属公司。版权所有。
如果满足以下条件,则允许以源代码和二进制形式重新分发和使用,无论是否经过修改:

  • 重新分发源代码必须保留上述版权声明、此条件列表和以下免责声明。
  • 以二进制形式重新分发必须在随分发提供的文档和或其他材料中复制上述版权声明、此条件列表和以下免责声明。

甲骨文及其附属公司或贡献者的姓名可用于认可或推广该软件派生的产品,而无需事先明确书面许可。

本软件按“原样”提供,不提供任何形式的保证。特此排除所有明示或暗示的条件、陈述和保证,
包括对适销性、特定用途的适用性或不侵权的任何暗示保证。
SUN 及其许可方不对被许可方因使用、修改或分发本软件或其衍生产品而遭受的或与之相关的任何损害或责任承担任何责任。
在任何情况下,SUN 或其许可方均不对因使用或无法使用软件,即使 SUN 已被告知存在此类损害的可能性。

您承认软件并非设计、许可或打算用于任何核设施的设计、建造、操作或维护。

2. 源代码

码云地址:src/test/jack/io/demo/ser/case1 · Jack魏/JDK1.1源码阅读学习 - 码云 - 开源中国 (gitee.com)


import java.io.*;
import java.net.*;
import java.util.*;

/**
 * 这个例子展示了如何使用套接字来发送和接收对象。
 * 该文件包含类Server,它从WriteSocket.java 文件中的WriteSocket 类接收对象。
 * Server 必须首先运行并等待WriteSocket 发送信息。
 *
 * 使用JDK1.1 & JDK1.2编译测试
 */
public class Server {

    /**
     * 创建 serversocket 并使用它的流来接收序列化的对象
     */
    public static void main(String args[]) {

        ServerSocket ser = null;
        Socket soc = null;
        String str = null;
        Date d = null;

        try {
            ser = new ServerSocket(8020);
            /*
             * 这将等待与此套接字建立连接。
             */
            soc = ser.accept();
            InputStream o = soc.getInputStream();
            ObjectInput s = new ObjectInputStream(o);
            str = (String) s.readObject();
            d = (Date) s.readObject();
            s.close();

            // 打印我们刚收到的
            System.out.println(str);
            System.out.println(d);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("Error during serialization");
            System.exit(1);
        }
    }
}

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * 这个例子展示了如何使用套接字和序列化来发送将被接收的对象(参见类 Server 查看接收部分)
 * <p>
 * 使用JDK1.1 & JDK1.2编译测试
 */
public class Client {

    public static void main(String args[]) {

        try {
            // 创建一个 Socket
            Socket soc = new Socket(InetAddress.getLocalHost(), 8020);

            // 将今天的日期序列化为与Socket关联的输出流
            OutputStream o = soc.getOutputStream();
            ObjectOutput s = new ObjectOutputStream(o);

            s.writeObject("Today's date");
            s.writeObject(new Date());
            s.flush();
            s.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("Error during serialization");
            System.exit(1);
        }
    }
}

3. 运行

如果你使用命令形式编译运行,请到本地源码地址cmd下面运行如下命令:
不知道指令如何编译运行java文件可参考:Java指令编译java文件

javac Server.java
javac Client.java 

然后首先运行Server:

  java Server

如果是Windows直接在开一个cmd命令窗口运行Client即可,如果是UNIX 系统上使用 Ctrl+Z 挂起服务器。
然后运行 Client:

  java Client

使用套接字和序列化,当前日期从客户端发送到服务器,然后服务器打印出日期。

这里我使用的是IDEA运行:


运行Server 运行Client客户端

4. 总结

首先就是Socket可能对于初学者来说比较困难,
这里可以先掌握可以通过Socket传输序列化文件即可,
后面有这方面的需求再去深入了解,我也会在以后慢慢讲解Socket。

紧接着我们再看,之前不是说不实现Serializable接口就不能序列化吗,
是的,没错,Date、Serializable都默认实现了Serializable接口(注意这里看到的是JDK1.8源码)。


String类
Date类

本实例一就已经讲解完了,如果有遗漏或者不清楚的地方可以留言哟~

相关文章

网友评论

      本文标题:Serializable官方实例解析01-对Sockets使用序

      本文链接:https://www.haomeiwen.com/subject/ffewyrtx.html