List of usage examples for java.net Socket close
public synchronized void close() throws IOException
From source file:POP3Demo.java
public static void main(String[] args) throws Exception { int POP3Port = 110; Socket client = new Socket("127.0.0.1", POP3Port); InputStream is = client.getInputStream(); BufferedReader sockin = new BufferedReader(new InputStreamReader(is)); OutputStream os = client.getOutputStream(); PrintWriter sockout = new PrintWriter(os, true); String cmd = "user Smith"; sockout.println(cmd);/* www . j a v a2s. c om*/ String reply = sockin.readLine(); cmd = "pass "; sockout.println(cmd + "popPassword"); reply = sockin.readLine(); cmd = "stat"; sockout.println(cmd); reply = sockin.readLine(); if (reply == null) return; cmd = "retr 1"; sockout.println(cmd); if (cmd.toLowerCase().startsWith("retr") && reply.charAt(0) == '+') do { reply = sockin.readLine(); System.out.println("S:" + reply); if (reply != null && reply.length() > 0) if (reply.charAt(0) == '.') break; } while (true); cmd = "quit"; sockout.println(cmd); client.close(); }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try {/* ww w . j a v a 2 s. c o m*/ serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine; KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
From source file:MainClass.java
public static void main(String[] args) throws IOException { SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(8080); ss.setNeedClientAuth(true);// w w w. j a va 2 s. c o m while (true) { try { 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); } System.out.println(""); StringBuffer buffer = new StringBuffer(); buffer.append("<HTML>\n"); buffer.append("<HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n"); buffer.append("<BODY>\n"); buffer.append("<H1>Success!</H1>\n"); buffer.append("</BODY>\n"); buffer.append("</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: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;/* w ww .jav 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:Who.java
public static void main(String[] v) { Socket s = null; PrintWriter out = null;/* w ww .j a v a 2 s . com*/ BufferedReader in = null; try { // Connect to port 79 (the standard finger port) on the host. String hostname = "www.java2s.com"; s = new Socket(hostname, 79); // Set up the streams out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); in = new BufferedReader(new InputStreamReader(s.getInputStream())); // Send a blank line to the finger server, telling it that we want // a listing of everyone logged on instead of information about an // individual user. out.print("\n"); out.flush(); // Send it out // Now read the server's response // The server should send lines terminated with \n or \r. String line; while ((line = in.readLine()) != null) { System.out.println(line); } System.out.println("Who's Logged On: " + hostname); } catch (IOException e) { System.out.println("Who's Logged On: Error"); } // Close the streams! finally { try { in.close(); out.close(); s.close(); } catch (Exception e) { } } }
From source file:HTTPServer.java
public static void main(String[] args) throws Exception { ServerSocket sSocket = new ServerSocket(1777); while (true) { System.out.println("Waiting for a client..."); Socket newSocket = sSocket.accept(); System.out.println("accepted the socket"); OutputStream os = newSocket.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(newSocket.getInputStream())); String inLine = null;//from w w w.j av a 2s . c om while (((inLine = br.readLine()) != null) && (!(inLine.equals("")))) { System.out.println(inLine); } System.out.println(""); StringBuffer sb = new StringBuffer(); sb.append("<html>\n"); sb.append("<head>\n"); sb.append("<title>Java \n"); sb.append("</title>\n"); sb.append("</head>\n"); sb.append("<body>\n"); sb.append("<H1>HTTPServer Works!</H1>\n"); sb.append("</body>\n"); sb.append("</html>\n"); String string = sb.toString(); byte[] byteArray = string.getBytes(); os.write("HTTP/1.0 200 OK\n".getBytes()); os.write(new String("Content-Length: " + byteArray.length + "\n").getBytes()); os.write("Content-Type: text/html\n\n".getBytes()); os.write(byteArray); os.flush(); os.close(); br.close(); newSocket.close(); } }
From source file:flink.iso8583.example.Client.java
public static void main(String[] args) throws Exception { Random rng = new Random(System.currentTimeMillis()); log.debug("Reading config"); mfact = ConfigParser.createFromClasspathConfig("flink/iso8583/example/config.xml"); mfact.setAssignDate(true);//from w ww . j ava2 s . co m mfact.setTraceNumberGenerator(new SimpleTraceGenerator((int) (System.currentTimeMillis() % 10000))); log.debug("Connecting to server"); Socket sock = new Socket("localhost", 9999); //Send 10 messages, then wait for the responses Client reader = new Client(sock); reader.start(); for (int i = 0; i < 10; i++) { IsoMessage req = mfact.newMessage(0x200); req.setValue(4, amounts[rng.nextInt(amounts.length)], IsoType.AMOUNT, 0); req.setValue(12, req.getObjectValue(7), IsoType.TIME, 0); req.setValue(13, req.getObjectValue(7), IsoType.DATE4, 0); req.setValue(15, req.getObjectValue(7), IsoType.DATE4, 0); req.setValue(17, req.getObjectValue(7), IsoType.DATE4, 0); req.setValue(37, new Long(System.currentTimeMillis() % 1000000), IsoType.NUMERIC, 12); req.setValue(41, data[rng.nextInt(data.length)], IsoType.ALPHA, 16); req.setValue(48, data[rng.nextInt(data.length)], IsoType.LLLVAR, 0); pending.put(req.getField(11).toString(), req); log.debug("Sending request " + req.getField(11)); req.write(sock.getOutputStream(), 2); } log.debug("Waiting for responses"); while (pending.size() > 0 && sock.isConnected()) { sleep(500); } reader.interrupt(); sock.close(); log.debug("DONE."); }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null;/*from w w w . ja va 2 s.c om*/ BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); }
From source file:ComplexCompany.java
public static void main(String args[]) throws Exception { Socket socket1; int portNumber = 1777; String str = ""; socket1 = new Socket(InetAddress.getLocalHost(), portNumber); ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream()); ComplexCompany comp = new ComplexCompany("A"); ComplexEmployee emp0 = new ComplexEmployee("B", 1000); comp.addPresident(emp0);//from ww w. ja v a 2 s . co m ComplexDepartment sales = new ComplexDepartment("C"); ComplexEmployee emp1 = new ComplexEmployee("D", 1200); sales.addManager(emp1); comp.addDepartment(sales); ComplexDepartment accounting = new ComplexDepartment("E"); ComplexEmployee emp2 = new ComplexEmployee("F", 1230); accounting.addManager(emp2); comp.addDepartment(accounting); ComplexDepartment maintenance = new ComplexDepartment("Maintenance"); ComplexEmployee emp3 = new ComplexEmployee("Greg Hladlick", 1020); maintenance.addManager(emp3); comp.addDepartment(maintenance); oos.writeObject(comp); while ((str = (String) ois.readObject()) != null) { System.out.println(str); oos.writeObject("bye"); if (str.equals("bye")) break; } ois.close(); oos.close(); socket1.close(); }
From source file:Connect.java
public static void main(String[] args) { try { // Handle exceptions below // Get our command-line arguments String hostname = args[0]; int port = Integer.parseInt(args[1]); String message = ""; if (args.length > 2) for (int i = 2; i < args.length; i++) message += args[i] + " "; // Create a Socket connected to the specified host and port. Socket s = new Socket(hostname, port); // Get the socket output stream and wrap a PrintWriter around it PrintWriter out = new PrintWriter(s.getOutputStream()); // Sent the specified message through the socket to the server. out.print(message + "\r\n"); out.flush(); // Send it now. // Get an input stream from the socket and wrap a BufferedReader // around it, so we can read lines of text from the server. BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); // Before we start reading the server's response tell the socket // that we don't want to wait more than 3 seconds s.setSoTimeout(3000);//from w w w.ja va 2 s. c o m // Now read lines from the server until the server closes the // connection (and we get a null return indicating EOF) or until // the server is silent for 3 seconds. try { String line; while ((line = in.readLine()) != null) // If we get a line System.out.println(line); // print it out. } catch (SocketTimeoutException e) { // We end up here if readLine() times out. System.err.println("Timeout; no response from server."); } out.close(); // Close the output stream in.close(); // Close the input stream s.close(); // Close the socket } catch (IOException e) { // Handle IO and network exceptions here System.err.println(e); } catch (NumberFormatException e) { // Bad port number System.err.println("You must specify the port as a number"); } catch (ArrayIndexOutOfBoundsException e) { // wrong # of args System.err.println("Usage: Connect <hostname> <port> message..."); } }