Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

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

Prototype

public Socket(InetAddress address, int port) throws IOException 

Source Link

Document

Creates a stream socket and connects it to the specified port number at the specified IP address.

Usage

From source file:davmail.smtp.TestSmtp.java

@Override
public void setUp() throws IOException {
    super.setUp();
    if (clientSocket == null) {
        // start gateway
        DavGateway.start();//  w  w w  .ja  v a  2 s  . co m
        clientSocket = new Socket("localhost", Settings.getIntProperty("davmail.smtpPort"));
        socketOutputStream = new BufferedOutputStream(clientSocket.getOutputStream());
        socketInputStream = new BufferedInputStream(clientSocket.getInputStream());

        String banner = readLine();
        assertNotNull(banner);
        //String credentials = (char) 0 + Settings.getProperty("davmail.username") + (char) 0 + Settings.getProperty("davmail.password");
        String credentials = Settings.getProperty("davmail.username") + (char) 0
                + Settings.getProperty("davmail.username") + (char) 0
                + Settings.getProperty("davmail.password");
        writeLine("AUTH PLAIN " + new String(new Base64().encode(credentials.getBytes())));
        assertEquals("235 OK Authenticated", readLine());
    }
    if (session == null) {
        session = ExchangeSessionFactory.getInstance(Settings.getProperty("davmail.username"),
                Settings.getProperty("davmail.password"));
    }
}

From source file:at.sti2.spark.streamer.SparkStreamer.java

private void stream(File fileToStream) {

    PrintWriter streamWriter = null;
    LineIterator lineIterator = null;//from   w w  w  .  j a v a 2 s .c o m

    long Counter = 0;

    try {
        sock = new Socket("localhost", port);
    } catch (IOException e) {
        logger.debug("Cannot connect to server.");
        System.exit(1);
    }
    logger.info("Connected.");

    try {
        streamWriter = new PrintWriter(sock.getOutputStream());
        lineIterator = FileUtils.lineIterator(fileToStream, "UTF-8");

        logger.info("Beginning to stream.");
        Date startStreaming = new Date();
        String line = null;
        while (lineIterator.hasNext()) {

            line = lineIterator.nextLine();
            streamWriter.println(line);
            Counter++;

            //            if (tripleCounter%1000 == 0){
            //               long currentTimepoint = (new Date()).getTime();
            //               System.out.println("Processing " + (1000/(currentTimepoint - timepoint)) + " triples/sec.");
            //               timepoint = currentTimepoint;
            //               streamWriter.flush();
            //            }
        }

        streamWriter.flush();

        Date endStreaming = new Date();
        logger.info("End of streaming.");
        logger.info("Streamed " + Counter + " triples/lines.");
        logger.info("Total streaming time " + (endStreaming.getTime() - startStreaming.getTime()) + " ms.");

    } catch (IOException e) {
        logger.error(e.getMessage());
    } finally {
        IOUtils.closeQuietly(streamWriter);
        lineIterator.close();
        logger.info("Disconnected.");
    }
}

From source file:net.sf.firemox.network.Client.java

@Override
public void run() {
    String entree;/*w w  w. j av a2 s . c o  m*/
    LoaderConsole.beginTask(LanguageManager.getString("wiz_network.creatingconnection") + "...", 2);
    InetAddress adr = null;
    try {
        // Connexion au serveur
        adr = InetAddress.getByName(Configuration.getString("ip"));
        clientSocket = new Socket(adr, port);
    } catch (IOException e) {
        // echec de la connexion au serveur
        JOptionPane.showMessageDialog(MagicUIComponents.magicForm,
                LanguageManager.getString("wiz_network.cannotconnectto", adr) + ", "
                        + LanguageManager.getString("wiz_network.port") + ":" + port + ". \n"
                        + LanguageManager.getString("wiz_network.port.invalid"),
                LanguageManager.getString("wiz_network.connectionpb"), JOptionPane.WARNING_MESSAGE);
        NetworkActor.cancelling = true;
        LoaderConsole.endTask();
    }

    // stopping?
    if (cancelling) {
        cancelConnexion();
        return;
    }
    LoaderConsole.beginTask(LanguageManager.getString("wiz_network.connecting"), 5);

    try {
        // Cration des flots d'entre/sortie
        outBin = clientSocket.getOutputStream();
        inBin = clientSocket.getInputStream();

        // need password?
        entree = MToolKit.readString(inBin);
        if (STR_PASSWD.equals(entree)) {
            // a password is need by this server
            if (passwd == null) {
                // ... but we haven't any
                LoaderConsole.beginTask(LanguageManager.getString("wiz_network.password.missed"));
                MToolKit.writeString(outBin, STR_NOPASSWD);
                // close stream
                IOUtils.closeQuietly(inBin);
                IOUtils.closeQuietly(outBin);
                // free pointers
                outBin = null;
                inBin = null;
            } else {
                // send our password
                MToolKit.writeString(outBin, new String(passwd));
                entree = MToolKit.readString(inBin);
                if (STR_WRONGPASSWD.equals(entree)) {
                    // wrong password
                    LoaderConsole.beginTask(LanguageManager.getString("wiz_network.password.invalid"));
                    // close stream
                    IOUtils.closeQuietly(inBin);
                    IOUtils.closeQuietly(outBin);
                    // free pointers
                    outBin = null;
                    inBin = null;
                }
            }
        }
        if (outBin != null && !STR_OK.equals(entree)) {
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.unknowncommand") + entree);
            // close stream
            IOUtils.closeQuietly(inBin);
            IOUtils.closeQuietly(outBin);
            // free pointers
            outBin = null;
            inBin = null;
        }
        if (outBin != null) {
            // send our version
            MToolKit.writeString(outBin, IdConst.VERSION);
            entree = MToolKit.readString(inBin);
            if (STR_WRONGVERSION.equals(entree)) {
                // wrong version
                LoaderConsole.beginTask(LanguageManager.getString("wiz_network.differentversionpb"));
                // close stream
                IOUtils.closeQuietly(inBin);
                IOUtils.closeQuietly(outBin);
                // free pointers
                outBin = null;
                inBin = null;
            }
        }
        if (outBin != null && !STR_OK.equals(entree)) {
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.unknowncommand") + entree);
            // close stream
            IOUtils.closeQuietly(inBin);
            IOUtils.closeQuietly(outBin);
            // free pointers
            outBin = null;
            inBin = null;
        }

        if (outBin != null) {
            /*
             * client is connected to the server client/serveur I am ...
             */
            MToolKit.writeString(outBin, nickName);
            // Opponent is ...
            String serverName = MToolKit.readString(inBin);
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.opponentis") + serverName, 10);

            // exchange shared string settings
            ((Opponent) StackManager.PLAYERS[1]).readSettings(serverName, nickName, inBin);
            ((You) StackManager.PLAYERS[0]).sendSettings(outBin);

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            // receive, and set the random seed
            long seed = Long.parseLong(MToolKit.readString(inBin));
            MToolKit.random.setSeed(seed);
            Log.info("Seed = " + seed);

            // read mana use option
            PayMana.useMana = Integer.parseInt(MToolKit.readString(inBin)) == 1;

            // read opponent response option
            WaitActivatedChoice.opponentResponse = Integer.parseInt(MToolKit.readString(inBin)) == 1;

            // Who starts?
            final StartingOption startingOption = StartingOption.values()[Integer
                    .valueOf(MToolKit.readString(inBin)).intValue()];
            final boolean serverStarts;
            switch (startingOption) {
            case random:
            default:
                serverStarts = MToolKit.random.nextBoolean();
                break;
            case server:
                serverStarts = true;
                break;
            case client:
                serverStarts = false;
            }

            if (serverStarts) {
                // server begins
                LoaderConsole.beginTask(LanguageManager.getString("wiz_network.opponentwillstart") + " (mode="
                        + startingOption.getLocaleValue() + ")", 15);
                StackManager.idActivePlayer = 1;
                StackManager.idCurrentPlayer = 1;
            } else {
                // client begins
                LoaderConsole.beginTask(LanguageManager.getString("wiz_network.youwillstarts") + " (mode="
                        + startingOption.getLocaleValue() + ")", 15);
                StackManager.idActivePlayer = 0;
                StackManager.idCurrentPlayer = 0;
            }

            // load rules from the MDB file
            dbStream = MdbLoader.loadMDB(MToolKit.mdbFile, StackManager.idActivePlayer);
            TableTop.getInstance().initTbs();

            // send our deck
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.sendingdeck"), 25);
            deck.send(outBin);
            StackManager.PLAYERS[0].zoneManager.giveCards(deck, dbStream);
            MToolKit.writeString(outBin, "%EOF%");
            outBin.flush();

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            // receive her/his deck
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.receivingdeck"), 55);
            readAndValidateOpponentDeck();

            // free resources
            LoaderConsole.setTaskPercent(100);

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            initBigPipe();
            MagicUIComponents.magicForm.initGame();
        }
    } catch (Throwable e) {
        NetworkActor.cancelling = true;
        LoaderConsole.endTask();
        cancelConnexion();
        Log.error(e);
        throw new RuntimeException(LanguageManager.getString("wiz_network.badconnection", adr), e);
    }
}

From source file:com.talis.platform.sequencing.zookeeper.ZkTestHelper.java

public boolean waitForServerUp(String hp, long timeout) {
    long start = System.currentTimeMillis();
    String split[] = hp.split(":");
    String host = split[0];//from  w  w w. ja v  a 2  s.  co m
    int port = Integer.parseInt(split[1]);
    while (true) {
        try {
            Socket sock = new Socket(host, port);
            BufferedReader reader = null;
            try {
                OutputStream outstream = sock.getOutputStream();
                outstream.write("stat".getBytes());
                outstream.flush();

                reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                String line = reader.readLine();
                if (line != null && line.startsWith("Zookeeper version:")) {
                    return true;
                }
            } finally {
                sock.close();
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (IOException e) {
            // ignore as this is expected
            LOG.info("server " + hp + " not up " + e);
        }

        if (System.currentTimeMillis() > start + timeout) {
            break;
        }
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            // ignore
        }
    }
    return false;
}

From source file:com.nmote.smpp.TCPLinkFactory.java

protected Socket createSocket() throws IOException {
    if (host == null) {
        throw new IOException("Remote host not specified");
    }/*from w  w  w .j a va 2  s  .  co  m*/
    Socket result = new Socket(host, port);
    if (timeout != 0) {
        result.setSoTimeout(timeout);
    }
    return result;
}

From source file:com.seyren.core.service.notification.IrcCatNotificationService.java

private void sendMessage(String ircCatHost, int ircCatPort, String message, String channel) throws IOException {
    Socket socket = new Socket(ircCatHost, ircCatPort);
    Closer closer = Closer.create();/* w ww  . j a v  a2s.  c  om*/
    try {
        Writer out = closer.register(new OutputStreamWriter(socket.getOutputStream()));
        out.write(format("%s %s\n", channel, message));
        out.flush();
    } catch (IOException e) {
        socket.close();
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.nohkumado.ipx800control.Ipx800Control.java

/**
 sendCmd//from  www .  ja  v  a  2  s.co m
 @param cmd the command to send
 opens a TCP port and sends a m2m command to the ipx, stores the eventual result in 
  return in @see returnMsg
 */
protected boolean sendCmd(String cmd) {
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    //System.out.println("sendcmd for "+cmd);
    try {
        //System.out.println("opening "+server+":"+port);
        socket = new Socket(server, port);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //System.out.println("about to send out cmd");
        out.println(cmd);
        //System.out.println("waiting for return");
        returnMsg = in.readLine();
        //System.out.println("return from ipx:"+returnMsg);
        if (returnMsg.matches("=")) {
            String[] parts = returnMsg.split("=");
            //String part1 = parts[0]; // Getin
            returnMsg = parts[1]; // value
        }
        out.close();
        in.close();
        socket.close();
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host " + server);
        return false;
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection");
        return false;
    }

    return true;
}

From source file:edu.stanford.junction.provider.jx.Junction.java

public Junction(URI uri, ActivityScript script, final JunctionActor actor) throws JunctionException {
    this.setActor(actor);

    mAcceptedInvitation = uri;//from   ww  w . j  a v  a2s  .  c  o  m
    mActivityScript = script;
    mSession = uri.getPath().substring(1);
    String host = uri.getHost();
    int port = uri.getPort();
    if (port == -1)
        port = JXServer.SERVER_PORT;

    // TODO: one connection per host (multiple subscriptions through one socket)
    // handle in Provider
    try {
        try {
            String my_ip = JunctionProvider.getLocalIpAddress();
            if (my_ip.equals(host)) {
                Log.d(TAG, "Starting local switchboard service");
                mSwitchboardServer = new JXServer();
                mSwitchboardServer.start();
            }
        } catch (Exception e) {
            Log.e(TAG, "Could not start local switchboard service", e);
        }

        Socket socket = new Socket(host, port);
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();
    } catch (IOException e) {
        Log.e(TAG, "Error connecting to socket", e);
    }

    int MAX_TIME = 20000;
    synchronized (mJoinLock) {
        if (!mJoinComplete) {
            try {
                mJoinLock.wait(MAX_TIME);
            } catch (InterruptedException e) {
                // Ignored
            }
        }
    }
    if (!mJoinComplete) {
        throw new JunctionException("Timeout while joining Junction session.");
    }

    triggerActorJoin(mActivityCreator);
}

From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java

@Test
public void testWriteClose() throws IOException {
    // Create a task to be executed following the acceptance of a new connection to the server socketChannel.
    // This task is the application entry point.
    // This task will write out the message "Hello and Goodbye" and then close the connection.
    ISocketChannelHandler socketChannelHandler = (nbContext, socket) -> WriteMessageTask.Builder.builder()
            .withByteBuffer(ByteBuffer.allocate(2048)).build()
            .writeMessage("Hello and Goodbye\n".getBytes(StandardCharsets.UTF_8), nbContext, socket,
                    () -> IOUtils.closeQuietly(socket), (e) -> LOG.error("Write failed", e));
    // create the server
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(/*from   w  w  w  .  j  a va2 s . co m*/
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            // Here we configure the provider for the listening socketChannel.  In this case,
            // a TCP server socketChannel will be created using the default TcpAcceptedConnectionHandler
            // to handle incoming connections and pass them off to the socketChannelHandler
            .withConnectorFactory(TcpConnectorFactory.Builder.builder()
                    // supply the application entry point
                    .withConnectedSocketTask(socketChannelHandler).build())
            .build();
    try {
        simpleNbServer.start();
        Socket socket = new Socket("localhost", 1111);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        String message = reader.readLine();
        System.out.println("Received message '" + message + "' from the server");
        Assert.assertEquals("Hello and Goodbye", message);
        socket.close();
    } finally {
        simpleNbServer.shutdown();
    }
}

From source file:org.mule.module.http.functional.listener.HttpListenerPersistentConnectionsTestCase.java

protected void assertConnectionClosesWithRequestConnectionCloseHeader(DynamicPort port, HttpVersion httpVersion)
        throws IOException, InterruptedException {
    Socket socket = new Socket("localhost", port.getNumber());
    sendRequest(socket, httpVersion);/*from  w w w.j  a v  a  2 s .com*/
    assertResponse(getResponse(socket), true);

    sendRequest(socket, httpVersion);
    assertResponse(getResponse(socket), true);

    PrintWriter writer = new PrintWriter(socket.getOutputStream());
    writer.println("GET / " + httpVersion);
    writer.println("Host: www.example.com");
    writer.println("Connection: close");
    writer.println("");
    writer.flush();
    assertResponse(getResponse(socket), true);

    sendRequest(socket, httpVersion);
    assertResponse(getResponse(socket), false);

    socket.close();
}