pl.umk.mat.olaf.lobby.lobbythread.LobbyThread.java Source code

Java tutorial

Introduction

Here is the source code for pl.umk.mat.olaf.lobby.lobbythread.LobbyThread.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.umk.mat.olaf.lobby.lobbythread;

import com.google.common.net.InetAddresses;
import pl.umk.mat.olaf.classes.Msg;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The Class LobbyThread.
 *
 * @author olaf
 */
public class LobbyThread extends Thread {

    /** The port. */
    private final Integer port;

    /** The server address. */
    private String serverAddress = null;

    /** The mask. */
    private int mask;

    /** The broadcast address. */
    private int broadcastAddress;

    /** The network address. */
    private int networkAddress;

    /** The rooms. */
    private ArrayList<Integer> rooms = null;

    /** The message. */
    private final Msg message = new Msg(null, null, "info", null);

    /** The client socket. */
    private Socket clientSocket;

    /**
     * Instantiates a new lobby thread.
     *
     * @param port the port
     */
    public LobbyThread(Integer port) {
        System.setProperty("java.net.preferIPv4Stack", "true");
        this.port = port;
    }

    /**
     * Find Server addres. Fist looks for chat server on localhost, next checks another interfaces.
     *
     * @throws SocketException the socket exception
     */
    public void findServerAddressAndReceiveInfo() throws SocketException {
        boolean serverFound = true;

        if (serverAddress == null) {
            Enumeration<NetworkInterface> netInterfaces = null;
            try {
                netInterfaces = NetworkInterface.getNetworkInterfaces();

                while (netInterfaces.hasMoreElements()) {
                    NetworkInterface ni = netInterfaces.nextElement();
                    Enumeration<InetAddress> address = ni.getInetAddresses();
                    while (address.hasMoreElements()) {
                        InetAddress addr = address.nextElement();
                        if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress()
                                && !(addr.getHostAddress().indexOf(":") > -1)) {
                            serverAddress = addr.getHostAddress();
                        }
                    }
                }
                if (serverAddress == null) {
                    serverAddress = "127.0.0.1";
                }
                /**
                 * check localhost connection
                 */
                System.out.println("Mam ju jaki adres...");
                try {
                    clientSocket = new Socket("localhost", port);
                } catch (IOException ex) {

                    System.out.println("There is no active severs on the local computer");
                    Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
                    serverFound = false;
                }
                if (serverFound == true) {
                    System.out.println("A jednak jest co na localhoscie!");
                    try {
                        rooms = returnRoomInfo(clientSocket);
                        serverAddress = "127.0.0.1";
                        clientSocket.close();
                    } catch (IOException | ClassNotFoundException ex) {
                        System.out.println("Error while closing socket!!");
                        Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else if (serverAddress != "127.0.0.1" && !serverFound) {
                    System.out.println("nie znalazem na porcie 127.0.0.01, szukam dalej!");
                    /**
                     * compute mask, network and broadcast ip address in the network
                     * and
                     * looks for running server
                     */
                    int maxMask = ~0;
                    mask = maxMask << (32 - NetworkInterface.getByInetAddress(Inet4Address.getByName(serverAddress))
                            .getInterfaceAddresses().get(0).getNetworkPrefixLength());
                    networkAddress = InetAddresses.coerceToInteger(InetAddresses.forString(serverAddress)) & mask;
                    broadcastAddress = (~mask) | (networkAddress);

                    System.out.println("Maska " + InetAddresses.fromInteger(mask).getHostAddress()
                            + " networkAddress " + InetAddresses.fromInteger(networkAddress).getHostAddress()
                            + " broadcast " + InetAddresses.fromInteger(broadcastAddress).getHostAddress());
                    /**
                     * check each address between networkAddress and broadcastAddress
                     */
                    for (int address = networkAddress + 1; address < broadcastAddress; address++) {
                        System.out.println("Adres: " + InetAddresses.fromInteger(address).getHostAddress());
                        serverFound = true;
                        try {

                            clientSocket = new Socket();
                            clientSocket.connect(new InetSocketAddress(InetAddresses.fromInteger(address), port),
                                    250);
                            serverFound = true;
                        } catch (IOException ex) {
                            serverFound = false;
                            Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        if (serverFound == true) {
                            serverAddress = InetAddresses.fromInteger(address).getHostAddress();
                            try {
                                rooms = returnRoomInfo(clientSocket);
                                clientSocket.close();
                            } catch (IOException | ClassNotFoundException ex) {
                                Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            break;
                        }

                    }
                }
                if (serverFound == false) {
                    serverAddress = "0.0.0.0";
                }

            } catch (SocketException e) {
                serverAddress = "127.0.0.1";
            } catch (UnknownHostException ex) {
                Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Function returns server address.
     *
     * @return the server address
     */
    public String getServerAddress() {
        return this.serverAddress;
    }

    /**
     * Returns info about Server.
     *
     * @return the server info
     */
    public ArrayList<Integer> getServerInfo() {
        return this.rooms;
    }

    /**
     * The function sends special message to server and retrieve HashMap from the server.
     * Function doesn't close the connection!
     *
     * @param acceptedSocket (accepted TCP connection)
     * @return the array list
     * @throws IOException Signals that an I/O exception has occurred.
     * @throws ClassNotFoundException the class not found exception
     */
    public ArrayList<Integer> returnRoomInfo(Socket acceptedSocket) throws IOException, ClassNotFoundException {
        ArrayList<Integer> rooms;
        InputStream reader = null;
        ObjectInputStream objectReader = null;
        OutputStream writer = null;
        ObjectOutputStream objectWriter = null;

        writer = acceptedSocket.getOutputStream();

        objectWriter = new ObjectOutputStream(writer);
        objectWriter.writeObject(message);
        System.out.println("Special message has been sended");
        reader = acceptedSocket.getInputStream();
        objectReader = new ObjectInputStream(reader);
        rooms = (ArrayList<Integer>) objectReader.readObject();
        System.out.println("I received message!");
        return rooms;
    }

    /* (non-Javadoc)
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        try {
            this.findServerAddressAndReceiveInfo();
        } catch (SocketException ex) {
            Logger.getLogger(LobbyThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}