List of usage examples for java.net Socket close
public synchronized void close() throws IOException
From source file:NewFingerServer.java
public static void main(String[] arguments) throws Exception { ServerSocketChannel sockChannel = ServerSocketChannel.open(); sockChannel.configureBlocking(false); InetSocketAddress server = new InetSocketAddress("localhost", 79); ServerSocket socket = sockChannel.socket(); socket.bind(server);/* ww w . j a va 2 s . co m*/ Selector selector = Selector.open(); sockChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { selector.select(); Set keys = selector.selectedKeys(); Iterator it = keys.iterator(); while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); it.remove(); if (selKey.isAcceptable()) { ServerSocketChannel selChannel = (ServerSocketChannel) selKey.channel(); ServerSocket selSocket = selChannel.socket(); Socket connection = selSocket.accept(); InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader is = new BufferedReader(isr); PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()), false); pw.println("NIO Finger Server"); pw.flush(); String outLine = null; String inLine = is.readLine(); if (inLine.length() > 0) { outLine = inLine; } readPlan(outLine, pw); pw.flush(); pw.close(); is.close(); connection.close(); } } } }
From source file:ComplexCompany.java
public static void main(String args[]) throws Exception { ServerSocket servSocket;// w w w.j a v a2s .c o m Socket fromClientSocket; int cTosPortNumber = 1777; String str; ComplexCompany comp; servSocket = new ServerSocket(cTosPortNumber); System.out.println("Waiting for a connection on " + cTosPortNumber); fromClientSocket = servSocket.accept(); ObjectOutputStream oos = new ObjectOutputStream(fromClientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(fromClientSocket.getInputStream()); while ((comp = (ComplexCompany) ois.readObject()) != null) { comp.printCompanyObject(); oos.writeObject("bye bye"); break; } oos.close(); fromClientSocket.close(); }
From source file:LoopingSocketServer.java
public static void main(String args[]) throws Exception { ServerSocket servSocket;//from ww w. ja va2 s .com Socket fromClientSocket; int cTosPortNumber = 1777; String str; servSocket = new ServerSocket(cTosPortNumber); System.out.println("Waiting for a connection on " + cTosPortNumber); fromClientSocket = servSocket.accept(); System.out.println("fromClientSocket accepted"); ObjectOutputStream oos = new ObjectOutputStream(fromClientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(fromClientSocket.getInputStream()); while ((str = (String) ois.readObject()) != null) { System.out.println("The message from client: " + str); if (str.equals("bye")) { oos.writeObject("bye bye"); break; } else { str = "Server returns " + str; oos.writeObject(str); } } oos.close(); fromClientSocket.close(); }
From source file:MainClass.java
public static void main(String args[]) throws Exception { System.setProperty("javax.net.ssl.keyStore", "lfkeystore2"); System.setProperty("javax.net.ssl.keyStorePassword", "wshr.ut"); SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); ServerSocket ss = ssf.createServerSocket(5432); while (true) { Socket s = ss.accept(); SSLSession session = ((SSLSocket) s).getSession(); Certificate[] cchain2 = session.getLocalCertificates(); for (int i = 0; i < cchain2.length; i++) { System.out.println(((X509Certificate) cchain2[i]).getSubjectDN()); }/*from w w w .j a va2 s.c om*/ System.out.println("Peer host is " + session.getPeerHost()); System.out.println("Cipher is " + session.getCipherSuite()); System.out.println("Protocol is " + session.getProtocol()); System.out.println("ID is " + new BigInteger(session.getId())); System.out.println("Session created in " + session.getCreationTime()); System.out.println("Session accessed in " + session.getLastAccessedTime()); PrintStream out = new PrintStream(s.getOutputStream()); out.println("Hi"); out.close(); s.close(); } }
From source file:ProxyTunnelDemo.java
public static void main(String[] args) throws Exception { ProxyClient proxyclient = new ProxyClient(); // set the host the proxy should create a connection to ///*from w w w . j av a 2 s . c o m*/ // Note: By default port 80 will be used. Some proxies only allow conections // to ports 443 and 8443. This is because the HTTP CONNECT method was intented // to be used for tunneling HTTPS. proxyclient.getHostConfiguration().setHost("www.yahoo.com"); // set the proxy host and port proxyclient.getHostConfiguration().setProxy("10.0.1.1", 3128); // set the proxy credentials, only necessary for authenticating proxies proxyclient.getState().setProxyCredentials(new AuthScope("10.0.1.1", 3128, null), new UsernamePasswordCredentials("proxy", "proxy")); // create the socket ProxyClient.ConnectResponse response = proxyclient.connect(); if (response.getSocket() != null) { Socket socket = response.getSocket(); try { // go ahead and do an HTTP GET using the socket Writer out = new OutputStreamWriter(socket.getOutputStream(), "ISO-8859-1"); out.write("GET http://www.yahoo.com/ HTTP/1.1\r\n"); out.write("Host: www.yahoo.com\r\n"); out.write("Agent: whatever\r\n"); out.write("\r\n"); out.flush(); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream(), "ISO-8859-1")); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } finally { // be sure to close the socket when we're done socket.close(); } } else { // the proxy connect was not successful, check connect method for reasons why System.out.println("Connect failed: " + response.getConnectMethod().getStatusLine()); System.out.println(response.getConnectMethod().getResponseBodyAsString()); } }
From source file:com.googlecode.shutdownlistener.ShutdownUtility.java
public static void main(String[] args) throws Exception { final ShutdownConfiguration config = ShutdownConfiguration.getInstance(); final String command; if (args.length > 0) { command = args[0];/* w ww. ja v a2s.com*/ } else { command = config.getStatusCommand(); } System.out.println("Calling " + config.getHost() + ":" + config.getPort() + " with command: " + command); final InetAddress hostAddress = InetAddress.getByName(config.getHost()); final Socket shutdownConnection = new Socket(hostAddress, config.getPort()); try { shutdownConnection.setSoTimeout(5000); final BufferedReader reader = new BufferedReader( new InputStreamReader(shutdownConnection.getInputStream())); final PrintStream writer = new PrintStream(shutdownConnection.getOutputStream()); try { writer.println(command); writer.flush(); while (true) { final String line = reader.readLine(); if (line == null) { break; } System.out.println(line); } } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(writer); } } finally { try { shutdownConnection.close(); } catch (IOException ioe) { } } }
From source file:com.gomoob.embedded.EmbeddedMongo.java
/** * Main entry of the program.// w w w . j a v a2s . c o m * * @param args arguments used to customize starting. * * @throws Exception If an error occured while executing the server. */ public static void main(String[] args) throws Exception { // Creates a default execution context, then the configuration of this context can be changed depending on the // command line parameters received. context = new Context(); // Parse the command line parseCommandLine(args); boolean terminated = false; System.out.println("MONGOD_HOST=" + context.getMongoContext().getNet().getServerAddress().getHostName()); System.out.println("MONGOD_PORT=" + context.getMongoContext().getNet().getPort()); System.out.println("SERVER_SOCKET_PORT=" + context.getSocketContext().getServerSocket().getLocalPort()); Socket socket = null; BufferedReader reader = null; Writer writer = null; while (!terminated) { socket = context.getSocketContext().getServerSocket().accept(); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new OutputStreamWriter(new DataOutputStream(socket.getOutputStream())); System.out.println("Waiting for command..."); String commandString = reader.readLine(); System.out.println(commandString); ICommand command = parseCommandString(commandString); IResponse response = command.run(context); writer.write(response.toJSON()); writer.close(); // If the current socket is opened close it if (!socket.isClosed()) { socket.close(); } // If stop is required terminated = response.isTerminationRequired(); } context.getSocketContext().getServerSocket().close(); }
From source file:MainClass.java
public static void main(String args[]) throws Exception { SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(443); ss.setNeedClientAuth(true);/*ww w . j av a2 s . co m*/ while (true) { Socket s = ss.accept(); SSLSession session = ((SSLSocket) s).getSession(); Certificate[] cchain = session.getPeerCertificates(); for (int j = 0; j < cchain.length; j++) { System.out.println(((X509Certificate) cchain[j]).getSubjectDN()); } PrintStream out = new PrintStream(s.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); String info = null; while ((info = in.readLine()) != null) { System.out.println("now got " + info); if (info.equals("")) break; } out.println("HTTP/1.0 200 OK\nMIME_version:1.0"); out.println("Content_Type:text/html"); String c = "<html> <head></head><body> <h1> Hi,</h1></Body></html>"; out.println("Content_Length:" + c.length()); out.println(""); out.println(c); out.close(); s.close(); in.close(); } }
From source file:MainClass.java
public static void main(String[] args) throws IOException { SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); ServerSocket ss = ssf.createServerSocket(8080); while (true) { try {// ww w.j a v a 2s. co m Socket s = ss.accept(); OutputStream out = s.getOutputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = null; while (((line = in.readLine()) != null) && (!("".equals(line)))) { System.out.println(line); } StringBuffer buffer = new StringBuffer(); buffer.append("<HTML><HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n"); buffer.append("<BODY>\n<H1>Success!</H1></BODY></HTML>\n"); String string = buffer.toString(); byte[] data = string.getBytes(); out.write("HTTP/1.0 200 OK\n".getBytes()); out.write(new String("Content-Length: " + data.length + "\n").getBytes()); out.write("Content-Type: text/html\n\n".getBytes()); out.write(data); out.flush(); out.close(); in.close(); s.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:cloudclient.Client.java
public static void main(String[] args) throws Exception { //Command interpreter CommandLineInterface cmd = new CommandLineInterface(args); String socket = cmd.getOptionValue("s"); String Host_IP = socket.split(":")[0]; int Port = Integer.parseInt(socket.split(":")[1]); String workload = cmd.getOptionValue("w"); try {/*w w w . j a va 2 s .co m*/ // make connection to server socket Socket client = new Socket(Host_IP, Port); InputStream inStream = client.getInputStream(); OutputStream outStream = client.getOutputStream(); PrintWriter out = new PrintWriter(outStream, true); BufferedReader in = new BufferedReader(new InputStreamReader(inStream)); System.out.println("Send tasks to server..."); //Start clock long startTime = System.currentTimeMillis(); //Batch sending tasks batchSendTask(out, workload); client.shutdownOutput(); //Batch receive responses batchReceiveResp(in); //End clock long endTime = System.currentTimeMillis(); double totalTime = (endTime - startTime) / 1e3; System.out.println("\nDone!"); System.out.println("Time to execution = " + totalTime + " sec."); // close the socket connection client.close(); } catch (IOException ioe) { System.err.println(ioe); } }