【问题标题】:Synchronizing variables over socket streams in Java [duplicate]在Java中通过套接字流同步变量[重复]
【发布时间】:2018-10-25 02:15:41
【问题描述】:

我有一个简单的 java 中简单区块链的 p2p 实现。

我正在尝试发送消息并在发送消息后等待立即响应,以更新客户端的本地“bloomchain”变量。

我尝试使用期货和在后台线程中运行的单线程执行器来执行此操作,但每次等待返回时,我都会遇到如下错误:

java.util.concurrent.ExecutionException: java.io.StreamCorruptedException: invalid type code: 00
java.util.concurrent.ExecutionException: java.io.StreamCorruptedException: invalid type code: 6F

我认为问题可能是等待我设置线程,因为我没有这种方式:

发送消息:

public void sendMessage(String message) {

        if (bloomChain.size() < 1) {
            System.out.println("Genesis Block");
            bloomChain.addBlock(new Block(message, "0"));

        } else {
            System.out.println("Augmented Block");
            bloomChain.addBlock(new Block(message, bloomChain.get(bloomChain.size() - 1).getPreviousHash()));
        }
        try {
            System.out.println("Sending Chain..");
            this.outputStream.writeObject(bloomChain);
            this.outputStream.flush();
            new Thread(()-> {
                try {
                    bloomChain = updateLocalChain();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            System.out.println("Chain Sent..");

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

    }

更新本地链:

public BloomChain updateLocalChain() throws ExecutionException, InterruptedException {
        Future<BloomChain> agreedChain = this.singleThreadExecutor.submit(new Callable<BloomChain>() {
            @Override
            public BloomChain call() throws IOException, ClassNotFoundException {
                Object newChain = null;
                while(true){
                    newChain = inputStream.readObject();
                    if(newChain instanceof BloomChain){
                        System.out.println(newChain.toString());
                        break;
                    }
                }
                return (BloomChain) newChain;
            }
        });
        return agreedChain.get();
    }

编辑: 在调试过程中,我发现程序收到了预期的响应,但还是产生了错误

【问题讨论】:

    标签: java multithreading sockets thread-safety p2p


    【解决方案1】:

    你是:

    1. 对每条消息使用一个新的ObjectInputStream,同时在所有消息的发送端使用相同的ObjectOutputStream
    2. 反之亦然。
    3. 从流中读取您尚未写入的其他内容。
    4. 向流中写入您未阅读的其他内容。
    5. 用一种方法写作,用非对称方法阅读。
    6. (补充)从/向底层流读取或写入某些内容,完全绕过对象流。

    为什么要使用线程同步地做某事是另一个谜。

    【讨论】:

    • 我可以确认我在所有活动中使用相同的ObjectOutputStreamObjectInputStream
    • 在调试过程中我发现程序确实收到了响应但还是产生了错误
    • 这些 cmets 都没有解决我提出的五个问题。
    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    相关资源
    最近更新 更多