List of usage examples for java.net Socket getLocalSocketAddress
public SocketAddress getLocalSocketAddress()
From source file:Main.java
public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 12900); System.out.println("Started client socket at " + socket.getLocalSocketAddress()); BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in)); String promptMsg = "Please enter a message (Bye to quit):"; String outMsg = null;//from w w w . j a v a 2s. c om System.out.print(promptMsg); while ((outMsg = consoleReader.readLine()) != null) { if (outMsg.equalsIgnoreCase("bye")) { break; } // Add a new line to the message to the server, // because the server reads one line at a time. socketWriter.write(outMsg); socketWriter.write("\n"); socketWriter.flush(); // Read and display the message from the server String inMsg = socketReader.readLine(); System.out.println("Server: " + inMsg); System.out.println(); // Print a blank line System.out.print(promptMsg); } socket.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { String serverName = args[0];/*from ww w .ja va2s . co m*/ int port = Integer.parseInt(args[1]); try { System.out.println("Connecting to " + serverName + " on port " + port); Socket client = new Socket(serverName, port); System.out.println("Just connected to " + client.getRemoteSocketAddress()); OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello from " + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " + in.readUTF()); client.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:paxos.Receiver.java
/** * Contoh kode program untuk node yang menerima paket. Idealnya dalam paxos * balasan juga dikirim melalui UnreliableSender. */// w w w .j a v a 2 s. c o m public static void main(String args[]) throws Exception { System.out.println("STARTED:"); int listenPort = 9876; /*DatagramSocket serverSocket = new DatagramSocket(listenPort); byte[] receiveData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength()); JSONObject receivedMessage = new JSONObject(sentence); System.out.println("RECEIVED: " + receivedMessage.optString("method")); }*/ try { ServerSocket serverSocket = new ServerSocket(listenPort); System.out.println("Server connected\n"); while (true) { Socket server = serverSocket.accept(); DataInputStream in = new DataInputStream(server.getInputStream()); System.out.println(in.readUTF()); DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!"); } } catch (Exception e) { e.printStackTrace(); System.out.println("It didn't work"); } }
From source file:Main.java
/** * Renders the details of a socket in the returned string * @param socket The socket to render/*from w w w .j a va 2s . co m*/ * @return the details of the socket as a string */ public static String render(Socket socket) { if (socket == null) return "NULL"; StringBuilder b = new StringBuilder("\nSocket ["); b.append("\n\tLocalPort:").append(socket.getLocalPort()); b.append("\n\tLocalAddress:").append(socket.getLocalAddress()); b.append("\n\tLocalSocketAddress:").append(socket.getLocalSocketAddress()); b.append("\n\tRemotePort:").append(socket.getPort()); b.append("\n\tRemoteAddress:").append(socket.getInetAddress()); b.append("\n\tRemoteSocketAddress:").append(socket.getRemoteSocketAddress()); b.append("\n\tChannel:").append(socket.getChannel()); b.append("\n\tHashCode:").append(socket.hashCode()); b.append("\n]"); return b.toString(); }
From source file:Main.java
public void run() { while (true) { try {/*w w w .j av a2s . c o m*/ System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "..."); Socket server = serverSocket.accept(); System.out.println("Just connected to " + server.getRemoteSocketAddress()); DataInputStream in = new DataInputStream(server.getInputStream()); System.out.println(in.readUTF()); DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!"); server.close(); } catch (SocketTimeoutException s) { System.out.println("Socket timed out!"); break; } catch (IOException e) { e.printStackTrace(); break; } } }
From source file:org.mule.transport.http.HttpConnector.java
public HttpMessageReceiver lookupReceiver(Socket socket, RequestLine requestLine) throws NoReceiverForEndpointException { int port = ((InetSocketAddress) socket.getLocalSocketAddress()).getPort(); String host = null;/*from w ww .ja v a 2s . com*/ for (MessageReceiver messageReceiver : receivers.values()) { if (messageReceiver.getEndpointURI().getPort() == port) { host = messageReceiver.getEndpointURI().getHost(); break; } } if (host == null) { String url = requestLine.getUrlWithoutParams(); throw new NoReceiverForEndpointException(HttpMessages.noReceiverFoundForUrl(url)); } String requestUriWithoutParams = requestLine.getUrlWithoutParams(); StringBuilder requestUri = new StringBuilder(80); if (requestUriWithoutParams.indexOf("://") == -1) { requestUri.append(getProtocol()).append("://").append(host).append(':').append(port); if (!ROOT_PATH.equals(requestUriWithoutParams)) { requestUri.append(requestUriWithoutParams); } } String uriStr = requestUri.toString(); // first check that there is a receiver on the root address if (logger.isTraceEnabled()) { logger.trace( "Looking up receiver on connector: " + getName() + " with URI key: " + requestUri.toString()); } HttpMessageReceiver receiver = (HttpMessageReceiver) lookupReceiver(uriStr); // If no receiver on the root and there is a request path, look up the // received based on the root plus request path if (receiver == null && !ROOT_PATH.equals(requestUriWithoutParams)) { if (logger.isDebugEnabled()) { logger.debug("Secondary lookup of receiver on connector: " + getName() + " with URI key: " + requestUri.toString()); } receiver = (HttpMessageReceiver) findReceiverByStem(getReceivers(), uriStr); if (receiver == null && logger.isWarnEnabled()) { logger.warn("No receiver found with secondary lookup on connector: " + getName() + " with URI key: " + requestUri.toString()); logger.warn("Receivers on connector are: " + MapUtils.toString(getReceivers(), true)); } } if (receiver == null) { throw new NoReceiverForEndpointException(HttpMessages.noReceiverFoundForUrl(requestUriWithoutParams)); } return receiver; }
From source file:com.devoteam.srit.xmlloader.http.bio.BIOSocketServerListener.java
public void run() { try {/* ww w .j a v a2 s . c o m*/ while (true) { // // Set up HTTP connection // GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL, "SocketServerListener secure=", secure, "waiting for a connection on socket"); Socket socket = serverSocket.accept(); GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL, "SocketServerListener secure=", secure, "got a connection"); DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection(); HttpParams params = new BasicHttpParams(); serverConnection.bind(socket, params); InetSocketAddress remoteInetSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); InetSocketAddress localInetSocketAddress = (InetSocketAddress) socket.getLocalSocketAddress(); String connectionName = "HTTPServerConnection" + Stack.nextTransactionId(); String remoteHost = remoteInetSocketAddress.getAddress().getHostAddress(); String remotePort = Integer.toString(remoteInetSocketAddress.getPort()); String localHost = localInetSocketAddress.getAddress().getHostAddress(); String localPort = Integer.toString(localInetSocketAddress.getPort()); BIOChannelHttp connHttp = new BIOChannelHttp(connectionName, localHost, localPort, remoteHost, remotePort, StackFactory.PROTOCOL_HTTP, secure); // // Start Server thread // BIOSocketServerHttp socketServerHttp = new BIOSocketServerHttp(serverConnection, connHttp); connHttp.setSocketServerHttp(socketServerHttp); StackFactory.getStack(StackFactory.PROTOCOL_HTTP).openChannel(connHttp); } } catch (Exception e) { GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.PROTOCOL, e, "Exception in SocketServerListener secure=" + secure); } GlobalLogger.instance().getApplicationLogger().warn(TextEvent.Topic.PROTOCOL, "SocketServerListener secure=", secure, "stopped"); }
From source file:org.apache.hadoop.hdfs.server.datanode.DataXceiver.java
public DataXceiver(Socket s, DataNode datanode, DataXceiverServer dataXceiverServer) { this.s = s;// w w w.j a v a 2 s.c o m this.datanode = datanode; this.dataXceiverServer = dataXceiverServer; dataXceiverServer.childSockets.put(s, s); remoteAddress = s.getRemoteSocketAddress().toString(); localAddress = s.getLocalSocketAddress().toString(); LOG.debug("Number of active connections is: " + datanode.getXceiverCount()); }
From source file:org.apache.hadoop.hdfs.server.datanode.CachingDataXceiver.java
private CachingDataXceiver(Socket s, SocketInputWrapper socketInput, DataNode datanode, CachingDataXceiverServer dataXceiverServer, BlockCache blockCache) throws IOException { super(new DataInputStream(new BufferedInputStream(socketInput, HdfsConstants.SMALL_BUFFER_SIZE))); this.s = s;/*from ww w .ja v a2 s . c o m*/ this.socketInputWrapper = socketInput; this.isLocal = s.getInetAddress().equals(s.getLocalAddress()); this.datanode = datanode; this.dnConf = datanode.getDnConf(); this.dataXceiverServer = dataXceiverServer; this.blockCache = blockCache; remoteAddress = s.getRemoteSocketAddress().toString(); localAddress = s.getLocalSocketAddress().toString(); if (LOG.isDebugEnabled()) { LOG.debug("Number of active connections is: " + datanode.getXceiverCount()); } }
From source file:org.apache.hadoop.raid.BlockFixer.java
/** * Send a generated block to a datanode. * @param datanode Chosen datanode name in host:port form. * @param blockContents Stream with the block contents. * @param corruptBlock Block identifying the block to be sent. * @param blockSize size of the block./*from ww w . ja v a2 s . c om*/ * @throws IOException */ private void sendFixedBlock(DatanodeInfo datanode, final InputStream blockContents, DataInputStream metadataIn, LocatedBlock block, long blockSize) throws IOException { InetSocketAddress target = NetUtils.createSocketAddr(datanode.name); Socket sock = SocketChannel.open().socket(); int readTimeout = getConf().getInt(BLOCKFIX_READ_TIMEOUT, HdfsConstants.READ_TIMEOUT); NetUtils.connect(sock, target, readTimeout); sock.setSoTimeout(readTimeout); int writeTimeout = getConf().getInt(BLOCKFIX_WRITE_TIMEOUT, HdfsConstants.WRITE_TIMEOUT); OutputStream baseStream = NetUtils.getOutputStream(sock, writeTimeout); DataOutputStream out = new DataOutputStream( new BufferedOutputStream(baseStream, FSConstants.SMALL_BUFFER_SIZE)); boolean corruptChecksumOk = false; boolean chunkOffsetOK = false; boolean verifyChecksum = true; boolean transferToAllowed = false; try { LOG.info("Sending block " + block.getBlock() + " from " + sock.getLocalSocketAddress().toString() + " to " + sock.getRemoteSocketAddress().toString() + " " + blockSize + " bytes"); RaidBlockSender blockSender = new RaidBlockSender(block.getBlock(), blockSize, 0, blockSize, corruptChecksumOk, chunkOffsetOK, verifyChecksum, transferToAllowed, metadataIn, new RaidBlockSender.InputStreamFactory() { @Override public InputStream createStream(long offset) throws IOException { // we are passing 0 as the offset above, so we can safely ignore // the offset passed return blockContents; } }); DatanodeInfo[] nodes = new DatanodeInfo[] { datanode }; DataTransferProtocol.Sender.opWriteBlock(out, block.getBlock(), 1, DataTransferProtocol.BlockConstructionStage.PIPELINE_SETUP_CREATE, 0, blockSize, 0, "", null, nodes, block.getBlockToken()); blockSender.sendBlock(out, baseStream); LOG.info("Sent block " + block.getBlock() + " to " + datanode.name); } finally { out.close(); } }