/** * Wait for Acknowledgement from other server. FIXME Please, not wait only for three characters, * better control that the wait ack message is correct. * * @throws java.io.IOException * @throws java.net.SocketTimeoutException */ protected void waitForAck() throws java.io.IOException { try { boolean ackReceived = false; boolean failAckReceived = false; ackbuf.clear(); int bytesRead = 0; int i = soIn.read(); while ((i != -1) && (bytesRead < Constants.ACK_COMMAND.length)) { bytesRead++; byte d = (byte) i; ackbuf.append(d); if (ackbuf.doesPackageExist()) { byte[] ackcmd = ackbuf.extractDataPackage(true).getBytes(); ackReceived = Arrays.equals(ackcmd, org.apache.catalina.tribes.transport.Constants.ACK_DATA); failAckReceived = Arrays.equals(ackcmd, org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA); ackReceived = ackReceived || failAckReceived; break; } i = soIn.read(); } if (!ackReceived) { if (i == -1) throw new IOException( sm.getString( "IDataSender.ack.eof", getAddress(), new Integer(socket.getLocalPort()))); else throw new IOException( sm.getString( "IDataSender.ack.wrong", getAddress(), new Integer(socket.getLocalPort()))); } else if (failAckReceived && getThrowOnFailedAck()) { throw new RemoteProcessException( "Received a failed ack:org.apache.catalina.tribes.transport.Constants.FAIL_ACK_DATA"); } } catch (IOException x) { String errmsg = sm.getString( "IDataSender.ack.missing", getAddress(), new Integer(socket.getLocalPort()), new Long(getTimeout())); if (SenderState.getSenderState(getDestination()).isReady()) { SenderState.getSenderState(getDestination()).setSuspect(); if (log.isWarnEnabled()) log.warn(errmsg, x); } else { if (log.isDebugEnabled()) log.debug(errmsg, x); } throw x; } finally { ackbuf.clear(); } }
/** @see com.thinkparity.network.NetworkConnection#connect() */ @Override public void connect() throws NetworkException { logger.logTraceId(); logger.logInfo("{0} - Connect.", getId()); Exception lastX = null; connected = false; for (final NetworkProxy proxy : proxies) { this.proxy = proxy; try { connectViaProxy(); setSocketOptions(); setSocketStreams(); logger.logInfo("{0} - Connected.", getId()); logger.logDebug( "{0} - Local: {1}:{2}", getId(), socket.getLocalAddress().getHostAddress(), socket.getLocalPort()); final InetSocketAddress remoteSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); logger.logDebug( "{0} - Remote: {1}:{2}", getId(), remoteSocketAddress.getAddress().getHostAddress(), remoteSocketAddress.getPort()); connected = true; break; } catch (final SocketException sx) { lastX = sx; } catch (final IOException iox) { lastX = iox; } } if (false == connected) { throw new NetworkException(lastX); } }
/** Test of TCP socket programming. */ public void listen() { ServerSocket socket = null; try { socket = new ServerSocket(PORT_NO); System.out.println("Opened server socket"); socket.setSoTimeout(TIMEOUT); connection = socket.accept(); System.out.println("Server: Received connection from port " + connection.getPort()); System.out.println("Server: local port: " + connection.getLocalPort()); ObjectInputStream iStream = new ObjectInputStream(connection.getInputStream()); MessageObject message = (MessageObject) iStream.readObject(); System.out.println("message received... by server"); System.out.println( "Server: received object, item=" + message.getItem() + " count: " + message.getCount()); // sendResponse("'Acknowledging message: object, item=" + message.getItem() + " count: " // + message.getCount()+"'"); connection.close(); socket.close(); } catch (SocketTimeoutException ste) { System.out.println("Timed out after " + TIMEOUT + " ms"); } catch (Exception e) { System.out.println(e.getClass().getName() + " at server: " + e.getMessage()); } } /*
@Test public void testSocketBind() throws Exception { final InetAddress localAddress = InetAddress.getByAddress(new byte[] {127, 0, 0, 1}); final int localPort = 8888; final InetAddress remoteAddress = InetAddress.getByAddress(new byte[] {10, 0, 0, 2}); final int remotePort = 80; final InetSocketAddress localSockAddress = new InetSocketAddress(localAddress, localPort); final InetSocketAddress remoteSockAddress = new InetSocketAddress(remoteAddress, remotePort); Mockito.when(socket.getLocalSocketAddress()).thenReturn(localSockAddress); Mockito.when(socket.getRemoteSocketAddress()).thenReturn(remoteSockAddress); Mockito.when(socket.getLocalAddress()).thenReturn(localAddress); Mockito.when(socket.getLocalPort()).thenReturn(localPort); Mockito.when(socket.getInetAddress()).thenReturn(remoteAddress); Mockito.when(socket.getPort()).thenReturn(remotePort); conn.bind(socket); Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString()); Assert.assertTrue(conn.isOpen()); Assert.assertEquals(8888, conn.getLocalPort()); Assert.assertEquals(80, conn.getRemotePort()); Assert.assertEquals( InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), conn.getLocalAddress()); Assert.assertEquals( InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), conn.getRemoteAddress()); }
public void executa() { try { cliente = new Socket(this.host, Servidor.serverPort); System.out.println( "PortaLocal do socket: " + cliente.getLocalPort() + "\nPorta conectada: " + cliente.getPort() + "\nLocalSocketAddress: " + cliente.getLocalSocketAddress() + "\nInetAddress: " + cliente.getInetAddress() + "\nRemoteSocketAddress: " + cliente.getRemoteSocketAddress()); System.out.println("Cliente conectado!"); System.out.println("testes"); // thread para receber mensagens do servidor ImpressoraCliente r = new ImpressoraCliente(cliente.getInputStream()); new Thread(r).start(); conectado = true; mainWindow.conectado(this); // cliente.close(); } catch (IOException e) { mainWindow.getTextConsole().setText("Não foi possível se conectar ao servidor."); conectado = false; System.err.println(e.getMessage()); } }
/** * initialize * * @param serverPort: Port des Servers * @param remoteServerAddress: Adresse des Servers * @param numberOfClient: Laufende Nummer des Test-Clients * @param messagelength: Laenge einer Nachricht * @param numberOfMessages: Anzahl zu sendender Nachrichten je Thread * @param clientThinkTime: Denkzeit des Test-Clients * @param sharedData: Gemeinsame Daten der Threads */ @Override public void initialize( int serverPort, String remoteServerAddress, int numberOfClient, int messageLength, int numberOfMessages, int clientThinkTime, SharedClientStatistics sharedData) { this.serverPort = serverPort; this.remoteServerAddress = remoteServerAddress; this.numberOfClient = numberOfClient; this.messageLength = messageLength; this.numberOfMessages = numberOfMessages; this.clientThinkTime = clientThinkTime; this.sharedData = sharedData; this.setName("EchoClient-".concat(String.valueOf(numberOfClient + 1))); threadName = getName(); // Verbindung zum Server aufbauen try { con = new Socket(remoteServerAddress, serverPort); out = new ObjectOutputStream(con.getOutputStream()); in = new ObjectInputStream(con.getInputStream()); localPort = con.getLocalPort(); log.debug(threadName + ": Verbindung zum Server aufgebaut mit Port " + localPort); log.debug(threadName + ": Registrierter Port: " + currentPort); } catch (Exception e) { log.debug("Exception beim Verbindungsaufbau: " + e); } }
void SocketTests() throws Exception { Socket s1 = new Socket(); test("Socket should be created with SO_REUSEADDR disabled"); check(!s1.getReuseAddress()); test("Socket.setReuseAddress(true)"); s1.setReuseAddress(true); check(s1.getReuseAddress()); test("Socket.setReuseAddress(false)"); s1.setReuseAddress(false); check(!s1.getReuseAddress()); /* bind to any port */ s1.bind(new InetSocketAddress(0)); test("Binding Socket to port already in use should throw " + "a BindException"); Socket s2 = new Socket(); try { s2.bind(new InetSocketAddress(s1.getLocalPort())); failed(); } catch (BindException e) { passed(); } s2.close(); s1.close(); }
private void onConnect(final ProxyMessage msg) throws IOException { Socket s; if (proxy == null) { s = new Socket(msg.ip, msg.port); } else { s = new SocksSocket(proxy, msg.ip, msg.port); } log.info("Connected to " + s.getInetAddress() + ":" + s.getPort()); ProxyMessage response = null; final InetAddress localAddress = s.getLocalAddress(); final int localPort = s.getLocalPort(); if (msg instanceof Socks5Message) { final int cmd = SocksProxyBase.SOCKS_SUCCESS; Socks5Message socks5Message = new Socks5Message(cmd, localAddress, localPort); socks5Message.setDnsResolver(dnsResolver); response = socks5Message; } else { final int cmd = Socks4Message.REPLY_OK; Socks4Message socks4Message = new Socks4Message(cmd, localAddress, localPort); socks4Message.setDnsResolver(dnsResolver); response = socks4Message; } response.write(out); startPipe(s); }
/** Waits for incoming connections and spins off threads to deal with them. */ private void listen() { Socket client = new Socket(); ServerThread st; /* Should only do this when it hasn't been told to shutdown. */ while (!shutdown) { /* Try to accept an incoming connection. */ try { client = serversock.accept(); if (debug) /* Output info about the client */ System.out.println( "Client on machine " + client.getInetAddress().getHostAddress() + " has connected on port " + client.getLocalPort() + "."); /* * Create a new thread to deal with the client, add it to the * vector of open connections. Finally, start the thread's * execution. Start method makes the threads go by calling their * run() methods. */ st = new ServerThread(client, this, clientcounter++, debug); serverthreads.add(st); st.start(); } catch (IOException e) { /* * Server Socket is closed, probably because a client told the * server to shutdown */ } } }
public static void printSocketParameters(Socket cl) throws SocketException { boolean SO_KEEPALIVE = cl.getKeepAlive(); boolean TCP_NODELAY = cl.getTcpNoDelay(); int SO_LINGER = cl.getSoLinger(); int SO_TIMEOUT = cl.getSoTimeout(); int SO_RCVBUF = cl.getReceiveBufferSize(); int SO_SNDBUF = cl.getSendBufferSize(); int trafficClassVal = cl.getTrafficClass(); /* 0 <= trafficClassVal <= 255 IPTOS_LOWCOST (0x02) IPTOS_RELIABILITY (0x04) IPTOS_THROUGHPUT (0x08) IPTOS_LOWDELAY (0x10) */ int remotePort = cl.getPort(); int localPort = cl.getLocalPort(); String localIP = getIPstr(cl.getLocalAddress()); String remoteIP = getIPstr(cl.getInetAddress()); System.out.println("Socket Paramaters :"); System.out.println("SO_KEEPAILVE = " + SO_KEEPALIVE + " TCP_NODELAY = " + TCP_NODELAY); System.out.println("SO_LINGER = " + SO_LINGER + " SO_TIMEOUT = " + SO_TIMEOUT); System.out.println("SO_RCVBUF = " + SO_RCVBUF + " SO_SNDBUF = " + SO_SNDBUF); System.out.println("Traffic Class = " + trafficClassVal); System.out.println("Local Address = " + localIP + ":" + localPort); System.out.println("Remote Address = " + remoteIP + ":" + remotePort); }
public String toString() { StringBuilder ret = new StringBuilder(); InetAddress local = null, remote = null; String local_str, remote_str; Socket tmp_sock = sock; if (tmp_sock == null) ret.append("<null socket>"); else { // since the sock variable gets set to null we want to make // make sure we make it through here without a nullpointer exception local = tmp_sock.getLocalAddress(); remote = tmp_sock.getInetAddress(); local_str = local != null ? Util.shortName(local) : "<null>"; remote_str = remote != null ? Util.shortName(remote) : "<null>"; ret.append( '<' + local_str + ':' + tmp_sock.getLocalPort() + " --> " + remote_str + ':' + tmp_sock.getPort() + "> (" + ((System.currentTimeMillis() - last_access) / 1000) + " secs old)"); } tmp_sock = null; return ret.toString(); }
/** Setup the sockets needed for the given transfer mode (either passive or active). */ private void setupTransferMode() { String resp = ""; if (passive) { debug("Switching to passive mode"); System.out.println("=> PASV"); out.println(commands[PASV]); resp = getResponse(); System.out.println(resp); /* If we've successfully entered passive mode, setup the socket */ if (resp.startsWith("227")) { String[] foo = resp.split(","); int pasvPort = new Integer(foo[4]) * 256 + new Integer(foo[5].replaceAll("[a-zA-Z).]+", "")); debug("Opening passive socket on " + serverAddr + ":" + pasvPort); try { pasvSock = new Socket(serverAddr, pasvPort, null, sock.getLocalPort() + 1); pasvIn = new BufferedReader(new InputStreamReader(pasvSock.getInputStream())); } catch (IOException e) { System.err.println(e.getMessage()); } } else { debug("Got invalid response from PASV command"); } } else { /* Active mode */ debug("Switching to active mode"); try { activeSock = new ServerSocket(0); } catch (IOException e) { System.err.println("Error creating active socket: " + e.getMessage()); } byte[] addr = sock.getLocalAddress().getAddress(); debug("Listening on local port " + activeSock.getLocalPort()); String portCmd = "PORT " + ((int) addr[0] & 0xFF) + "," + ((int) addr[1] & 0xFF) + "," + ((int) addr[2] & 0xFF) + "," + ((int) addr[3] & 0xFF) + "," + activeSock.getLocalPort() / 256 + "," + activeSock.getLocalPort() % 256; System.out.println("=> " + portCmd); out.println(portCmd); System.out.println(getResponse()); } }
public String toString() { return socket.getInetAddress() + ":" + socket.getPort() + "(localport=" + socket.getLocalPort() + ")"; }
/** Get something unique for this connection. */ public String connectionId() { if (selectionKey == null) { return "null.null"; } else { Socket socket = ((SocketChannel) selectionKey.channel()).socket(); return "" + socket.getLocalPort() + "." + socket.getPort(); } }
private String describeConnection(Socket s) { return String.format( "from %s:%d to %s:%d", s.getInetAddress().getHostAddress(), s.getPort(), s.getLocalAddress().getHostAddress(), s.getLocalPort()); }
public FrontendConnection(SocketChannel channel) { super(channel); Socket socket = channel.socket(); this.host = socket.getInetAddress().getHostAddress(); this.port = socket.getPort(); this.localPort = socket.getLocalPort(); this.handler = new FrontendAuthenticator(this); }
public ServerMessageGetterSender(Socket socket) { this.socket = socket; // Get input and output streams in reverse order of ClientMessageGetterSender class try { this.out = new ObjectOutputStream(socket.getOutputStream()); } catch (IOException ioe) { System.out.println("Could not get ObjectOutputStream on socket: " + socket.getLocalPort()); } try { this.in = new ObjectInputStream(socket.getInputStream()); } catch (IOException ioe) { System.out.println("Could not get ObjectInputStream on socket: " + socket.getLocalPort()); } }
@Override public void disconnect() throws LWTRTException { log.trace("disconnect, localport:" + socket.getLocalPort()); try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Create a new message and record the source ip and port * * @param aSocket The socket through which the message will be read. * @return The {@link AS2Message} to use and never <code>null</code>. */ @Nonnull protected AS2Message createMessage(@Nonnull final Socket aSocket) { final AS2Message aMsg = new AS2Message(); aMsg.setAttribute(CNetAttribute.MA_SOURCE_IP, aSocket.getInetAddress().toString()); aMsg.setAttribute(CNetAttribute.MA_SOURCE_PORT, Integer.toString(aSocket.getPort())); aMsg.setAttribute(CNetAttribute.MA_DESTINATION_IP, aSocket.getLocalAddress().toString()); aMsg.setAttribute(CNetAttribute.MA_DESTINATION_PORT, Integer.toString(aSocket.getLocalPort())); aMsg.setAttribute(AS2Message.ATTRIBUTE_RECEIVED, Boolean.TRUE.toString()); return aMsg; }
public ClientApp(String serverName, int serverPort) { response = new Scanner(System.in); System.out.print("Enter your name: "); playerName = response.nextLine(); System.out.println(); System.out.println(playerName + ": Establishing connection. Please wait ..."); logger.info(playerName + ": Establishing connection. Please wait ..."); player = new Player(playerName); try { this.socket = new Socket(serverName, serverPort); this.ID = socket.getLocalPort(); System.out.println(); logger.info("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#="); System.out.println("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#="); logger.info("WELCOME TO GAME OF THE SURVIVAL OF THE FITTEST"); System.out.println("WELCOME TO GAME OF THE SURVIVAL OF THE FITTEST"); logger.info("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=\n"); System.out.println("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=\n"); System.out.println(playerName + ": Connected to server: " + socket.getInetAddress()); logger.info(playerName + ": Connected to server: " + socket.getInetAddress()); System.out.println(playerName + ": Connected to portid: " + socket.getLocalPort()); logger.info(playerName + ": Connected to portid: " + socket.getLocalPort()); this.start(); sendJoinMessageAcross = sendJoinMessage(playerName, socket.getInetAddress().getHostAddress()); send(sendJoinMessageAcross); logger.info("Client sent to server: " + sendJoinMessageAcross); } catch (UnknownHostException uhe) { System.err.println(ID + ": Unknown Host"); logger.error(ID + ": Unknown Host"); System.out.println(uhe.getMessage()); logger.info(uhe.getMessage()); } catch (IOException ioe) { logger.error(ID + ": Unexpected exception"); System.out.println(ID + ": Unexpected exception"); System.out.println(ioe.getMessage()); logger.info(ioe.getMessage()); } }
public void run() { int port = -1; Socket toServer = null; try { toServer = new Socket("localhost", this.pingPort); toServer.setSoTimeout(MAX_HEARTBEAT_DELAY); port = toServer.getLocalPort(); in = new BufferedReader(new InputStreamReader(toServer.getInputStream())); out = new PrintWriter(toServer.getOutputStream(), true); while (true) { long start = System.currentTimeMillis(); String data = in.readLine(); if (HEARTBEAT.equals(data)) { log("Got heartbeat for main class " + this.forClass); } else if (SHUTDOWN.equals(data)) { if (!honorShutdownMsg) continue; log("Client received shutdown message from server. Shutting Down..."); System.exit(0); } else if (ARE_YOU_ALIVE.equals(data)) { out.println(forClass); out.flush(); } else { throw new Exception("Doesn't recognize data: " + data); } long elapsed = System.currentTimeMillis() - start; if (elapsed > MAX_HEARTBEAT_DELAY) { throw new Exception("Client took too long to response."); } } } catch (Exception e) { log(e.getClass() + ": " + Arrays.asList(e.getStackTrace())); log( "Didn't get heartbeat for at least " + MAX_HEARTBEAT_DELAY + " milliseconds. Killing self (port " + port + ")."); } finally { log("Ping thread exiting port (" + port + ")"); if (toServer != null) { try { toServer.close(); } catch (IOException e) { throw new RuntimeException(e); } } System.exit(EXIT_CODE); } }
public boolean sendMessage(Message messageToSend) { try { out.writeObject(messageToSend); } catch (IOException ioe) { System.out.println("Could not write to socket: " + socket.getLocalPort()); return false; } return true; }
private String getSockAddress() { StringBuilder sb = new StringBuilder(); if (sock != null) { sb.append(sock.getLocalAddress().getHostAddress()).append(':').append(sock.getLocalPort()); sb.append(" - ") .append(sock.getInetAddress().getHostAddress()) .append(':') .append(sock.getPort()); } return sb.toString(); }
/** @return pretty print of 'this' */ @Override public String toString() { return "" + (socket.isConnected() ? "tcp://" + socket.getInetAddress() + ":" + socket.getPort() + "@" + socket.getLocalPort() : (localLocation != null ? localLocation : remoteLocation)); }
@Override public void run() { try { while (running) { final Socket socket = serverSocket.accept(); log.info("Accepting Client on port " + socket.getLocalPort()); executorService.submit(new Acceptor(socket)); } } catch (IOException e) { if (running) e.printStackTrace(); } }
@Override public void send(Object pdu) throws LWTRTException { log.trace("send from " + socket.getLocalPort() + " to " + socket.getPort()); if (socket.isClosed()) { throw new LWTRTException("Socket is closed"); } try { oout.writeObject(pdu); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override public Object receive() throws LWTRTException { log.trace("receive, localport:" + socket.getLocalPort()); if (socket.isClosed()) { throw new LWTRTException("Socket is closed"); } try { return oin.readObject(); } catch (IOException e) { throw new LWTRTException("Verbindung wurde disconnected"); } catch (ClassNotFoundException e) { throw new LWTRTException(e); } }
public String toString() { Socket tmp_sock = sock; if (tmp_sock == null) return "<null socket>"; InetAddress local = tmp_sock.getLocalAddress(), remote = tmp_sock.getInetAddress(); String local_str = local != null ? Util.shortName(local) : "<null>"; String remote_str = remote != null ? Util.shortName(remote) : "<null>"; return String.format( "%s:%s --> %s:%s (%d secs old) [%s] [recv_buf=%d]", local_str, tmp_sock.getLocalPort(), remote_str, tmp_sock.getPort(), TimeUnit.SECONDS.convert(getTimestamp() - last_access, TimeUnit.NANOSECONDS), status(), receiver != null ? receiver.bufferSize() : 0); }
public void run() { logger.info("Server Started"); while (true) { try { nodeSd = server.accept(); } catch (IOException e) { logger.error("Accept failed."); logger.error(e); } /* start a new thread to handle the new node */ // Thread t = new Thread(new Node(nodeSd, false)); Thread t = new Thread(new HandleNewNode(nodeSd.getInetAddress(), nodeSd.getLocalPort(), nodeSd)); t.start(); } }
public void init(String server) { try { socket = new Socket(server, BANKPORT); System.out.println("Socket created on the local port " + socket.getLocalPort()); System.out.println( "A connection established with the remote port " + socket.getPort() + " at " + socket.getInetAddress().toString()); in = new Scanner(socket.getInputStream()); out = new PrintWriter(socket.getOutputStream()); System.out.println("I/O setup done."); } catch (IOException exception) { } }