Example usage for java.net InetSocketAddress getPort

List of usage examples for java.net InetSocketAddress getPort

Introduction

In this page you can find the example usage for java.net InetSocketAddress getPort.

Prototype

public final int getPort() 

Source Link

Document

Gets the port number.

Usage

From source file:old.server.loginserver.LoginServer.java

private boolean registerPlayer(final InetSocketAddress sender_address, final JSONObject jo)
        throws JSONException {
    // TODO: Configurable limitations for names and etc.
    // TODO: Check role indexes to the bound of array(enum)
    final String name = jo.getString(CommonPacketConsts.ITEM_USERNAME);
    CommonPacketConsts.ENUM_PLAYER_ROLE role = CommonPacketConsts.ENUM_PLAYER_ROLE.values()[jo
            .getInt(CommonPacketConsts.PLAYER_ROLE)];

    final GameServerInfo gsi = getFirstAvailableGameServer();

    if (gsi == null) {
        enqueueMessage(MessageToBeEnqueued.make(PacketFactory.make(PACKET_TYPE_RESULT_FAIL, CLIENT_LOGINSERVER),
                sender_address));//w w  w .j a  va  2  s  .  c  o  m
        return false;
    }

    PlayerInfo player_info = new PlayerInfo(sender_address, gsi.getServerAddress(), name, role, (short) 0);

    if (!logged_players.add(player_info)) {
        enqueueMessage(MessageToBeEnqueued.make(PacketFactory.make(PACKET_TYPE_RESULT_FAIL, CLIENT_LOGINSERVER),
                sender_address));
        return false;
    }

    enqueueMessage(MessageToBeEnqueued.make(PacketFactory.make(PACKET_TYPE_RESULT_SUCCESS, CLIENT_LOGINSERVER),
            sender_address));

    enqueueMessage(MessageToBeEnqueued.make(PacketFactory.make(CLIENT_LOGINSERVER, name,
            sender_address.getHostString(), sender_address.getPort(), role), gsi.getServerAddress()));
    player_info.setConnected(true);

    return true;
}

From source file:edu.umass.cs.reconfiguration.ActiveReplica.java

@SuppressWarnings({ "unchecked", "unused" })
@Deprecated//from  w  w  w .  j a  v  a  2  s  .  c om
private AddressMessenger<JSONObject> initClientMessenger() {
    AbstractPacketDemultiplexer<JSONObject> pd = null;
    Messenger<InetSocketAddress, JSONObject> cMsgr = null;
    Set<IntegerPacketType> appTypes = null;
    if ((appTypes = this.appCoordinator.getAppRequestTypes()) == null || appTypes.isEmpty())
        return null;
    try {
        int myPort = (this.nodeConfig.getNodePort(getMyID()));
        if (getClientFacingPort(myPort) != myPort) {
            log.log(Level.INFO, "{0} creating client messenger at {1}:{2}", new Object[] { this,
                    this.nodeConfig.getBindAddress(getMyID()), getClientFacingPort(myPort) });

            if (this.messenger.getClientMessenger() == null
                    || this.messenger.getClientMessenger() != this.messenger) {
                MessageNIOTransport<InetSocketAddress, JSONObject> niot = null;
                InetSocketAddress isa = new InetSocketAddress(this.nodeConfig.getBindAddress(getMyID()),
                        getClientFacingPort(myPort));
                cMsgr = new JSONMessenger<InetSocketAddress>(
                        niot = new MessageNIOTransport<InetSocketAddress, JSONObject>(isa.getAddress(),
                                isa.getPort(),
                                /* Client facing demultiplexer is single
                                 * threaded to keep clients from
                                 * overwhelming the system with request
                                 * load. */
                                (pd = new ReconfigurationPacketDemultiplexer()),
                                ReconfigurationConfig.getClientSSLMode()));
                if (!niot.getListeningSocketAddress().equals(isa))
                    throw new IOException("Unable to listen on specified client facing socket address " + isa);
            } else if (this.messenger.getClientMessenger() instanceof Messenger)
                ((Messenger<NodeIDType, ?>) this.messenger.getClientMessenger())
                        .addPacketDemultiplexer(pd = new ReconfigurationPacketDemultiplexer(0));
            pd.register(this.appCoordinator.getAppRequestTypes(), this);
        }
    } catch (IOException e) {
        e.printStackTrace();
        log.severe(this + ":" + e.getMessage());
        System.exit(1);
    }
    return cMsgr != null ? cMsgr : (AddressMessenger<JSONObject>) this.messenger;
}

From source file:com.couchbase.client.ViewConnection.java

/**
 * Create ViewNode connections and queue them up for connect.
 *
 * This method also defines the connection params for each connection,
 * including the default settings like timeouts and the user agent string.
 *
 * @param addrs addresses of all the nodes it should connect to.
 * @return Returns a list of the ViewNodes.
 * @throws IOException// w w  w.  ja  v a  2s .co m
 */
private List<ViewNode> createConnections(List<InetSocketAddress> addrs) throws IOException {

    List<ViewNode> nodeList = new LinkedList<ViewNode>();

    for (InetSocketAddress a : addrs) {
        HttpParams params = new SyncBasicHttpParams();
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
                .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000)
                .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
                .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
                .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
                .setParameter(CoreProtocolPNames.USER_AGENT, "Couchbase Java Client 1.0.2");

        HttpProcessor httpproc = new ImmutableHttpProcessor(
                new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(),
                        new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(), });

        AsyncNHttpClientHandler protocolHandler = new AsyncNHttpClientHandler(httpproc,
                new MyHttpRequestExecutionHandler(), new DefaultConnectionReuseStrategy(),
                new DirectByteBufferAllocator(), params);
        protocolHandler.setEventListener(new EventLogger());

        AsyncConnectionManager connMgr = new AsyncConnectionManager(new HttpHost(a.getHostName(), a.getPort()),
                NUM_CONNS, protocolHandler, params, new RequeueOpCallback(this));
        getLogger().info("Added %s to connect queue", a.getHostName());

        ViewNode node = connFactory.createViewNode(a, connMgr);
        node.init();
        nodeList.add(node);
    }

    return nodeList;
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);/*from w  w  w  . jav a  2s .co m*/
    }
    try {
        if (connectTimeout > 0 && sock.getSoTimeout() == 0) {
            sock.setSoTimeout(connectTimeout);
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting socket to " + remoteAddress + " with timeout " + connectTimeout);
        }
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        this.log.debug("Starting handshake");
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.ApacheClientHttpInvoker.java

/**
 * Builds a SSL Socket Factory for the Apache HTTP Client.
 *//*from   w w  w.  j ava  2  s  .co m*/
private SchemeLayeredSocketFactory getSSLSocketFactory(final UrlBuilder url, final BindingSession session) {
    // get authentication provider
    AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);

    // check SSL Socket Factory
    final SSLSocketFactory sf = authProvider.getSSLSocketFactory();
    if (sf == null) {
        // no custom factory -> return default factory
        return org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
    }

    // check hostame verifier and use default if not set
    final HostnameVerifier hv = (authProvider.getHostnameVerifier() == null
            ? new BrowserCompatHostnameVerifier()
            : authProvider.getHostnameVerifier());

    if (hv instanceof X509HostnameVerifier) {
        return new org.apache.http.conn.ssl.SSLSocketFactory(sf, (X509HostnameVerifier) hv);
    }

    // build new socket factory
    return new SchemeLayeredSocketFactory() {

        @Override
        public boolean isSecure(Socket sock) {
            return true;
        }

        @Override
        public Socket createSocket(HttpParams params) throws IOException {
            return sf.createSocket();
        }

        @Override
        public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
                final InetSocketAddress localAddress, final HttpParams params) throws IOException {

            Socket sock = socket != null ? socket : createSocket(params);
            if (localAddress != null) {
                sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
                sock.bind(localAddress);
            }

            int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
            int soTimeout = HttpConnectionParams.getSoTimeout(params);

            try {
                sock.setSoTimeout(soTimeout);
                sock.connect(remoteAddress, connTimeout);
            } catch (SocketTimeoutException ex) {
                closeSocket(sock);
                throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out!");
            }

            String host;
            if (remoteAddress instanceof HttpInetSocketAddress) {
                host = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
            } else {
                host = remoteAddress.getHostName();
            }

            SSLSocket sslSocket;
            if (sock instanceof SSLSocket) {
                sslSocket = (SSLSocket) sock;
            } else {
                int port = remoteAddress.getPort();
                sslSocket = (SSLSocket) sf.createSocket(sock, host, port, true);
            }
            verify(hv, host, sslSocket);

            return sslSocket;
        }

        @Override
        public Socket createLayeredSocket(final Socket socket, final String host, final int port,
                final HttpParams params) throws IOException {
            SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, true);
            verify(hv, host, sslSocket);

            return sslSocket;
        }
    };
}

From source file:com.taobao.adfs.distributed.DistributedServer.java

void createRpcServer() throws IOException {
    InetSocketAddress socAddr = NetUtils.createSocketAddr(serverName);
    int rpcHandlerNumber = conf.getInt("distributed.server.handler.number", 100);
    for (int i = 0; i < 10; ++i) {
        try {//  w  w  w .ja  va2s.com
            rpcServer = RPC.getServer(this, socAddr.getHostName(), socAddr.getPort(), rpcHandlerNumber, false,
                    conf);
            break;
        } catch (IOException e) {
            if (i == 9 || !Utilities.getFirstCause(e).getClass().equals(BindException.class))
                throw e;
            Utilities.sleepAndProcessInterruptedException(1000, logger);
        }
    }
    try {
        rpcServer.start();
        log(Level.INFO, " create rpc server with address=", serverName);
    } catch (Throwable t) {
        log(Level.ERROR, " fail to create rpc server with address=", serverName, t);
        rpcServer = null;
        throw new IOException(t);
    }
}

From source file:eu.stratosphere.nephele.jobmanager.JobManager.java

public JobManager(ExecutionMode executionMode) throws Exception {

    final String ipcAddressString = GlobalConfiguration.getString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY,
            null);/* ww w  . j  a v a 2 s  . c o  m*/

    InetAddress ipcAddress = null;
    if (ipcAddressString != null) {
        try {
            ipcAddress = InetAddress.getByName(ipcAddressString);
        } catch (UnknownHostException e) {
            throw new Exception("Cannot convert " + ipcAddressString + " to an IP address: " + e.getMessage(),
                    e);
        }
    }

    final int ipcPort = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY,
            ConfigConstants.DEFAULT_JOB_MANAGER_IPC_PORT);

    // Read the suggested client polling interval
    this.recommendedClientPollingInterval = GlobalConfiguration.getInteger(
            ConfigConstants.JOBCLIENT_POLLING_INTERVAL_KEY, ConfigConstants.DEFAULT_JOBCLIENT_POLLING_INTERVAL);

    // Load the job progress collector
    this.eventCollector = new EventCollector(this.recommendedClientPollingInterval);

    // Register simple job archive
    int archived_items = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_WEB_ARCHIVE_COUNT,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_ARCHIVE_COUNT);
    if (archived_items > 0) {
        this.archive = new MemoryArchivist(archived_items);
        this.eventCollector.registerArchivist(archive);
    } else {
        this.archive = null;
    }

    // Create the accumulator manager, with same archiving limit as web
    // interface. We need to store the accumulators for at least one job.
    // Otherwise they might be deleted before the client requested the
    // accumulator results.
    this.accumulatorManager = new AccumulatorManager(Math.min(1, archived_items));

    // Load the input split manager
    this.inputSplitManager = new InputSplitManager();

    // Determine own RPC address
    final InetSocketAddress rpcServerAddress = new InetSocketAddress(ipcAddress, ipcPort);

    // Start job manager's IPC server
    try {
        final int handlerCount = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_IPC_HANDLERS_KEY,
                ConfigConstants.DEFAULT_JOB_MANAGER_IPC_HANDLERS);
        this.jobManagerServer = RPC.getServer(this, rpcServerAddress.getHostName(), rpcServerAddress.getPort(),
                handlerCount);
        this.jobManagerServer.start();
    } catch (IOException e) {
        throw new Exception("Cannot start RPC server: " + e.getMessage(), e);
    }

    LOG.info("Starting job manager in " + executionMode + " mode");

    // Try to load the instance manager for the given execution mode
    // Try to load the scheduler for the given execution mode
    if (executionMode == ExecutionMode.LOCAL) {
        try {
            this.instanceManager = new LocalInstanceManager();
        } catch (Throwable t) {
            throw new Exception("Cannot instantiate local instance manager: " + t.getMessage(), t);
        }
    } else {
        final String instanceManagerClassName = JobManagerUtils.getInstanceManagerClassName(executionMode);
        LOG.info("Trying to load " + instanceManagerClassName + " as instance manager");
        this.instanceManager = JobManagerUtils.loadInstanceManager(instanceManagerClassName);
        if (this.instanceManager == null) {
            throw new Exception("Unable to load instance manager " + instanceManagerClassName);
        }
    }

    // Try to load the scheduler for the given execution mode
    final String schedulerClassName = JobManagerUtils.getSchedulerClassName(executionMode);
    LOG.info("Trying to load " + schedulerClassName + " as scheduler");

    // Try to get the instance manager class name
    this.scheduler = JobManagerUtils.loadScheduler(schedulerClassName, this, this.instanceManager);
    if (this.scheduler == null) {
        throw new Exception("Unable to load scheduler " + schedulerClassName);
    }

    // Load profiler if it should be used
    if (GlobalConfiguration.getBoolean(ProfilingUtils.ENABLE_PROFILING_KEY, false)) {
        final String profilerClassName = GlobalConfiguration.getString(ProfilingUtils.JOBMANAGER_CLASSNAME_KEY,
                "eu.stratosphere.nephele.profiling.impl.JobManagerProfilerImpl");
        this.profiler = ProfilingUtils.loadJobManagerProfiler(profilerClassName, ipcAddress);
        if (this.profiler == null) {
            throw new Exception("Cannot load profiler");
        }
    } else {
        this.profiler = null;
        LOG.debug("Profiler disabled");
    }
}

From source file:org.apache.hadoop.hdfs.qjournal.server.JournalNodeJournalSyncer.java

void recoverSegment(InetSocketAddress jn, EditLogFile relf, SyncTask task) throws IOException {
    try {/*from w w w.j  av  a 2s  . co m*/
        // we are looking for finalized segments that we do not have
        // we only care about segments within the range

        final long remoteStartTxid = relf.getFirstTxId();
        final long remoteEndTxid = relf.getLastTxId();

        if (remoteStartTxid >= task.recoveryStartTxid && remoteStartTxid <= task.recoveryEndTxid
                && remoteEndTxid <= task.recoveryEndTxid && !relf.isInProgress()
                && !task.containsValidSegment(relf)) {

            String name = "[" + remoteStartTxid + " : " + remoteEndTxid + "]";

            LOG.info(logMsg + "attempting recovery for segment " + name + " for journal id: "
                    + task.journal.getJournalId());

            // path to download
            String path = GetJournalEditServlet.buildPath(task.journal.getJournalId(), remoteStartTxid,
                    task.journal.getJournalStorage(), 0);

            // url to download
            URL url = new URL("http", jn.getAddress().getHostAddress(), jn.getPort(), path.toString());

            // download temporary file
            File syncedTmpFile = task.journal.getJournalStorage().getSyncLogTemporaryFile(relf.getFirstTxId(),
                    relf.getLastTxId(), now());

            // .tmp file will not interfere with storage
            syncedTmpFile = task.journal.syncLog(now(), relf.getFirstTxId(), url, name, syncedTmpFile);

            // final destination of the file
            File syncedDestFile = task.journal.getJournalStorage().getSyncLogDestFile(relf.getFirstTxId(),
                    relf.getLastTxId());

            if (syncedDestFile == null) {
                throwIOException(logMsg + " Error when recovering log " + relf);
            }

            // synchronized on journal so no files can be changed
            synchronized (task.journal) {
                // move away our local copy of the segment
                EditLogFile localCorruptedFile = null;
                try {
                    localCorruptedFile = task.getInprogressSegment(remoteStartTxid);
                    if (localCorruptedFile != null) {
                        localCorruptedFile.moveAsideCorruptFile();
                    }
                } catch (Exception e) {
                    LOG.warn(logMsg + "exception when marking segment: " + localCorruptedFile + " as corrupt.",
                            e);
                }
                // move tmp file to finalized log segment
                FileUtil.replaceFile(syncedTmpFile, syncedDestFile);
            }

            // add the segment to the list so we do not recover it again
            task.addValidSegment(relf);
            LOG.info(logMsg + "successfully recovered segment " + name + " for journal id: "
                    + task.journal.getJournalId());
            InjectionHandler.processEvent(InjectionEvent.QJM_JOURNALNODE_RECOVERY_COMPLETED);
        }
    } catch (Exception e) {
        LOG.warn(logMsg + "exception when recovering segment: " + relf.toColonSeparatedString()
                + " when trying with journal node: " + jn, e);
    }
}

From source file:com.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();//ww w  .j  a va  2 s .  c o m

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}