List of usage examples for java.net Socket getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.sshtools.j2ssh.agent.SshAgentClient.java
SshAgentClient(boolean isForwarded, String application, Socket socket) throws IOException { log.info("New SshAgentClient instance created"); this.socket = socket; this.in = socket.getInputStream(); this.out = socket.getOutputStream(); this.isForwarded = isForwarded; registerMessages();//from w ww .ja v a 2 s . com if (isForwarded) { sendForwardingNotice(); } else { sendVersionRequest(application); } }
From source file:jhttpp2.Jhttpp2HTTPSession.java
public Jhttpp2HTTPSession(Jhttpp2Server server, Socket client) { try {//w w w . j a v a 2s. co m in = new Jhttpp2ClientInputStream(server, this, client.getInputStream());// ,true); out = new BufferedOutputStream(client.getOutputStream()); this.server = server; this.client = client; } catch (IOException e_io) { try { client.close(); } catch (IOException e_io2) { log.debug("Error while closing client (kinda expected)" + e_io); } log.warn("Error while creating IO-Streams: ", e_io); return; } start(); }
From source file:net.jadler.JadlerStubbingIntegrationTest.java
@Test @Ignore/*from www. j av a 2 s . c om*/ public void havingURISockets() throws IOException { onRequest().havingURIEqualTo("/").respond().withStatus(201); final Socket sock = new Socket("localhost", port()); final OutputStream out = sock.getOutputStream(); out.write("GET / HTTP/1.1\r\nHost:localhost\r\n\r\n".getBytes()); InputStream in = sock.getInputStream(); int b; while ((b = in.read()) != -1) { char res = (char) b; System.out.print(res); } }
From source file:net.java.jless.tls.Record.java
/** * Set the connect cipher states to null and writeSeqNums to zero. Create * new socket connection to server//from www . j a v a 2 s . co m */ public void setSocket(Socket s) throws TLSException { try { clientWriteCipherIsNull = true; serverWriteCipherIsNull = true; clientWriteSeqNum = 0; serverWriteSeqNum = 0; outs = new BufferedOutputStream(s.getOutputStream()); ins = new BufferedInputStream(s.getInputStream()); } catch (Exception e) { e.printStackTrace(); throw new TLSException("Error in Record.reset(): " + e.getMessage()); } }
From source file:lockstep.LockstepServer.java
/** * Implements the handshake protocol server side, setting up the UDP * connection, queues and threads for a specific client. * To be run in parallel threads, one for each client, as they need * to synchronize to correctly setup the lockstep protocol. * It signals success through a latch or failure through interruption to the * server thread./* w w w . j a v a2s . c o m*/ * * @param tcpSocket Connection with the client, to be used in handshake only * @param firstFrameNumber Frame number to initialize the lockstep protocol * @param barrier Used for synchronization with concurrent handshake sessions * @param latch Used to signal the successful completion of the handshake session. * @param server Used to signal failure of the handshake sessions, via interruption. */ private void serverHandshakeProtocol(Socket tcpSocket, int firstFrameNumber, CyclicBarrier barrier, CountDownLatch latch, LockstepServer server) { try (ObjectOutputStream oout = new ObjectOutputStream(tcpSocket.getOutputStream());) { oout.flush(); try (ObjectInputStream oin = new ObjectInputStream(tcpSocket.getInputStream());) { //Receive hello message from client and reply LOG.info("Waiting an hello from " + tcpSocket.getInetAddress().getHostAddress()); oout.flush(); ClientHello hello = (ClientHello) oin.readObject(); LOG.info("Received an hello from " + tcpSocket.getInetAddress().getHostAddress()); DatagramSocket udpSocket = new DatagramSocket(); openSockets.add(udpSocket); InetSocketAddress clientUDPAddress = new InetSocketAddress( tcpSocket.getInetAddress().getHostAddress(), hello.clientUDPPort); udpSocket.connect(clientUDPAddress); int assignedClientID; do { assignedClientID = (new Random()).nextInt(100000) + 10000; } while (!this.clientIDs.add(assignedClientID)); LOG.info("Assigned hostID " + assignedClientID + " to " + tcpSocket.getInetAddress().getHostAddress() + ", sending helloReply"); ServerHelloReply helloReply = new ServerHelloReply(udpSocket.getLocalPort(), assignedClientID, clientsNumber, firstFrameNumber); oout.writeObject(helloReply); ConcurrentHashMap<Integer, TransmissionQueue> clientTransmissionFrameQueues = new ConcurrentHashMap<>(); this.transmissionFrameQueueTree.put(assignedClientID, clientTransmissionFrameQueues); ACKSet clientAckQueue = new ACKSet(); ackQueues.put(assignedClientID, clientAckQueue); clientReceiveSetup(assignedClientID, udpSocket, firstFrameNumber, clientTransmissionFrameQueues); barrier.await(); //Send second reply ClientsAnnouncement announcement = new ClientsAnnouncement(); announcement.clientIDs = ArrayUtils.toPrimitive(this.clientIDs.toArray(new Integer[0])); oout.writeObject(announcement); clientTransmissionSetup(assignedClientID, firstFrameNumber, udpSocket, clientTransmissionFrameQueues); //Wait for other handshakes to reach final step barrier.await(); oout.writeObject(new SimulationStart()); //Continue with execution latch.countDown(); } } catch (IOException | ClassNotFoundException ioEx) { LOG.fatal("Exception at handshake with client"); LOG.fatal(ioEx); server.interrupt(); } catch (InterruptedException | BrokenBarrierException inEx) { //Interruptions come from failure in parallel handshake sessions, and signal termination } }
From source file:gridool.communication.transport.tcp.GridOioClient.java
public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException { final Socket socket; try {// ww w . j a va2 s .c o m socket = SocketUtils.openSocket(sockAddr, 0, 2000L, 3); } catch (IOException e) { LOG.error("failed to connect: " + sockAddr, e); throw new GridException(e); } final byte[] b = GridUtils.toBytes(msg); // TODO sendfile support if (LOG.isDebugEnabled()) { LOG.debug("Sending a message [" + msg.getMessageId() + " (" + b.length + " bytes)] to a node [" + sockAddr + "] using a socket [" + socket + ']'); } try { OutputStream sockout = socket.getOutputStream(); sockout.write(b); sockout.flush(); NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN) } catch (IOException ioe) { final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr + ']'; LOG.error(errmsg, ioe); throw new GridException(errmsg, ioe); } catch (Throwable e) { LOG.fatal(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException("Unexpected exception was caused", e); } finally { NetUtils.closeQuietly(socket); } }
From source file:com.springrts.springls.ServerThread.java
public boolean redirectAndKill(Socket socket) { if (!context.getServer().isRedirectActive()) { return false; }//from w ww. j av a 2 s. c o m try { (new PrintWriter(socket.getOutputStream(), true)).println( String.format("REDIRECT %s", context.getServer().getRedirectAddress().getHostAddress())); socket.close(); } catch (IOException ex) { return false; } return true; }
From source file:Network.Dengue.CDengueHandler.java
@Override public void update(Observable o, Object arg) { int intReturn = 1; Socket objSocket = (Socket) arg; StringBuilder objSB = new StringBuilder(); try {/*from w w w. j a v a2s . c o m*/ BufferedReader objReader = new BufferedReader(new InputStreamReader(objSocket.getInputStream())); objSB.append(objReader.readLine()); new MDengue().addCluster(objSB.toString()); CNotificationManager.notifiyDengue(); CPublisherManager.publishDengue(); } catch (IOException | ParseException ex) { System.out.println(ex); intReturn = -1; } finally { try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()), StandardCharsets.US_ASCII.name())) { objWriter.append(intReturn + ""); } catch (Exception ex) { System.out.println(ex); } } }
From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java
public void sendSample(InetAddress host, int port, JSONObject sample) throws InterruptedException, IOException { int trials = 120; int timeout = 500; Socket client = null; while (client == null || !client.isConnected()) { try {/*w w w . ja va2 s. c o m*/ client = new Socket(host, port); } catch (IOException e) { Thread.sleep(timeout); if (trials == 0) { logger.error(e.getMessage()); client.close(); throw new IOException(); } else { trials -= 1; } } } PrintWriter writer = new PrintWriter(client.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream())); writer.println(sample.toString()); writer.flush(); String code = reader.readLine(); assertEquals("SUCCESS", code); }
From source file:com.honnix.cheater.admin.AdminServer.java
public void run() { while (true) { synchronized (lock) { if (!isStarted) { break; }/* w ww .j ava 2s. c om*/ } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (SocketException e) { // Here we can assume that if there is SocketException, it means // the socket has been closed. break; } catch (IOException e) { LOG.error("Failed accepting admin socket connection.", e); continue; } if (hasClient) { try { PrintWriter pw = new PrintWriter(clientSocket.getOutputStream()); pw.println("Someone else is administrating me."); pw.flush(); clientSocket.close(); } catch (IOException e) { LOG.warn("Error operating client socket.", e); } } else { hasClient = true; new AdminClient(this, clientSocket).start(); } } }