集册 Java实例教程 创建套接字连接并跨线路发送可序列化对象

创建套接字连接并跨线路发送可序列化对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

555
创建套接字连接并跨线发送可序列化的对象
/**
N o  w  J a v a . c o m - 时  代  Java
**/

import java.io.IOException;

import java.io.InputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.OutputStream;

import java.net.InetAddress;

import java.net.InetSocketAddress;

import java.nio.channels.AsynchronousServerSocketChannel;

import java.nio.channels.AsynchronousSocketChannel;

import java.nio.channels.Channels;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Future;

import java.util.concurrent.TimeoutException;


public class Main {

  InetSocketAddress hostAddress;/* 来 自 n o w    j a v a  . c o m*/

  void start() throws Exception {

    hostAddress = new InetSocketAddress(InetAddress.getByName("127.0.0.1"),1234);


    Thread serverThread = new Thread(() -> {serverStart();});


    serverThread.start();


    Thread clientThread = new Thread(() -> {clientStart();});

    clientThread.start();


  }


  private void clientStart() {

    try {

      try (AsynchronousSocketChannel clientSocketChannel = AsynchronousSocketChannel.open()) {

        Future<Void> connectFuture = clientSocketChannel.connect(hostAddress);

        connectFuture.get();

        OutputStream os = Channels.newOutputStream(clientSocketChannel);

        try (ObjectOutputStream oos = new ObjectOutputStream(os)) {

          for (int i = 0; i < 5; i++) {

            oos.writeObject("Look at me " + i);

            Thread.sleep(1000);

          }

          oos.writeObject("EOF");

        }

      }

    } catch (IOException | InterruptedException | ExecutionException e) {

      e.printStackTrace();

    }


  }


  private void serverStart() {

    try {

      AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open().bind(hostAddress);

      Future<AsynchronousSocketChannel> serverFuture = serverSocketChannel.accept();

      final AsynchronousSocketChannel clientSocket = serverFuture.get();

      System.out.println("Connected!");

      if ((clientSocket != null) && (clientSocket.isOpen())) {

        try (InputStream connectionInputStream = Channels.newInputStream(clientSocket)) {

          ObjectInputStream ois = null;

          ois = new ObjectInputStream(connectionInputStream);

          while (true) {

            Object object = ois.readObject();

            if (object.equals("EOF")) {

              clientSocket.clos
展开阅读全文