集册 Java实例教程 从服务器套接字接收消息

从服务器套接字接收消息

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

517
从服务器套接字接收消息

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;/*from 时 代 J a v a 公 众 号 - nowjava.com*/

import java.net.ServerSocket;

import java.net.Socket;


public class Receiver {

  ServerSocket reciever;

  Socket connection = null;

  ObjectOutputStream out;

  ObjectInputStream in;

  String packet, ack, data = "";

  int i = 0, sequence = 0;
  /*
  时代Java公众号 提 供
  */


  Receiver() {

  }


  public void run() {


    try {

      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      reciever = new ServerSocket(2005, 10);

      System.out.println("waiting for connection...");

      connection = reciever.accept();

      sequence = 0;

      System.out.println("Connection established   :");

      out = new ObjectOutputStream(connection.getOutputStream());

      out.flush();

      in = new ObjectInputStream(connection.getInputStream());

      out.writeObject("connected    .");


      do {

        try {

          packet = (String) in.readObject();


          if (Integer.valueOf(packet.substring(0, 1)) == sequence) {

            data += packet.substring(1);

            sequence = (sequence == 0) ? 1 : 0;

            System.out.println("\n\nreceiver         >" + packet);

          } else {

            System.out.println("\n\nreceiver         >" + packet + "   duplicate data");

          }

          if (i < 3) {

            out.writeObject(String.valueOf(sequence));

            i++;

          } else {

            out.writeObject(String.valueOf((sequence + 1) % 2));

            i = 0;

          }

        } catch (Exception e) {

        }

      } while (!packet.equals("end"));


      System.out.println("Data recived=" + data);

      out.writeObject("connection ended    .");

    } catch (
展开阅读全文