Package voxo.server.threads

Source Code of voxo.server.threads.NetworkReceiver

package voxo.server.threads;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.EnumSet;

import voxo.common.entities.Packet;
import voxo.common.enums.EnumVerbose;
import voxo.server.controllers.ServerController;

public class NetworkReceiver implements Runnable {

  private ServerController  c;
  private boolean        go;
  ServerSocket        srvSock  = null;
  Socket            sock  = null;
  InputStream          in    = null;
  ObjectInputStream      oin    = null;

  public NetworkReceiver(ServerController c) {
    this.c = c;
  }

  @Override
  public void run() {
    try {
      srvSock = new ServerSocket(54445);
      this.go = true;

      while (this.go) {
        try {
          srvSock.setReuseAddress(true);
          srvSock.setSoTimeout(5000);
         
          sock = srvSock.accept();
          in = sock.getInputStream();
          oin = new ObjectInputStream(in);

          Packet p = (Packet) oin.readObject(); // Get the packet

          new PacketParser(sock.getInetAddress(), p).start();
        } catch (SocketTimeoutException e) {
        } catch (IOException | ClassNotFoundException e) {
          this.c.getVerbose().addConsoleMsg(e, EnumSet.of(EnumVerbose.ToConsole, EnumVerbose.ToLog));
        } finally {
          if (oin != null) {
            oin.close();
            oin = null;
          }
          if (in != null) {
            in.close();
            in = null;
          }
          if (sock != null) {
            sock.close();
            sock = null;
          }
        }
      }
     
      srvSock.close();
      srvSock = null;
     
    } catch (IOException e) {
      killSocket();
      this.c.getVerbose().addConsoleMsg(e, EnumSet.of(EnumVerbose.ToConsole, EnumVerbose.ToLog));
    }
  }

  class PacketParser extends Thread {
    private Packet    p;
    private InetAddress  ip;

    public PacketParser(InetAddress ip, Packet p) {
      this.p = p;
      this.ip = ip;
    }

    @Override
    public void run() {
      c.parsePacket(ip, p);
    }
  }

  public void killSocket() {
    this.go = false;
    try {
      if (oin != null) {
        oin.close();
        oin = null;
      }
      if (in != null) {
        in.close();
        in = null;
      }
      if (sock != null) {
        sock.close();
        sock = null;
      }
      if (srvSock != null) {
        srvSock.close();
        srvSock = null;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
TOP

Related Classes of voxo.server.threads.NetworkReceiver

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.