List of usage examples for java.net Socket Socket
public Socket(InetAddress address, int port) throws IOException
From source file:ComplexCompany.java
public static void main(String args[]) throws Exception { Socket socket1;/* w w w .j a v a 2 s . c o m*/ 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); 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:org.atmosphere.tictactoe42a9x.ElementalHttpGet.java
public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {/*from w ww . j av a2 s .c om*/ String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa" }; for (int i = 0; i < targets.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:net.ElementalHttpGet.java
public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("www.baidu.com", 80); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {//from w ww . j a v a2 s . c om String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample?a=1&b=2", "/somewhere%20in%20pampa" }; for (int i = 0; i < targets.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:clientpaxos.ClientPaxos.java
/** * @param args the command line arguments *//*from w w w. jav a 2s . c o m*/ public static void main(String[] args) throws IOException, InterruptedException, Exception { // TODO code application logic here String host = ""; int port = 0; try (BufferedReader br = new BufferedReader(new FileReader("ipserver.txt"))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); if (line != null) { host = line; line = br.readLine(); if (line != null) { port = Integer.parseInt(line); } } } scanner = new Scanner(System.in); //System.out.print("Input server IP hostname : "); //host = scan.nextLine(); //System.out.print("Input server Port : "); //port = scan.nextInt(); //scan.nextLine(); tcpSocket = new Socket(host, port); System.out.println("Connected"); Thread t = new Thread(new StringGetter()); t.start(); while (true) { sleep(100); if (!voteInput) { System.out.print("COMMAND : "); } //send msg to server String msg = scanner.next(); //if ((day && isAlive == 1) || (!day && role.equals("werewolf") && isAlive == 1)) { ParseCommand(msg); //} } }
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);/* w w w. j a v a2 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:com.sourcecode.youku.ElementalHttpPost.java
public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {// ww w.j av a 2 s . c om HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"), new ByteArrayEntity("This is the second test request".getBytes("UTF-8")), new InputStreamEntity(new ByteArrayInputStream( "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:j8583.example.Client.java
public static void main(String[] args) throws Exception { Random rng = new Random(System.currentTimeMillis()); log.debug("Reading config"); mfact = ConfigParser.createFromClasspathConfig("j8583/example/config.xml"); mfact.setAssignDate(true);/*from w ww .j a v a 2s . c o m*/ mfact.setTraceNumberGenerator(new SimpleTraceGenerator((int) (System.currentTimeMillis() % 10000))); System.err.println("Connecting to server"); Socket sock = new Socket("localhost", 9999); // Send 10 messages, then wait for the responses Client client = new Client(sock); Thread reader = new Thread(client, "j8583-client"); 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, 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); System.err.println(String.format("Sending request %s", req.getField(11))); req.write(sock.getOutputStream(), 2); } log.debug("Waiting for responses"); while (pending.size() > 0 && sock.isConnected()) { Thread.sleep(500); } client.stop(); reader.interrupt(); log.debug("DONE."); }
From source file:io.aos.protocol.http.httpcommon.ElementalHttpGet.java
public static void main(String... args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {/*w w w.j a v a 2 s. c om*/ String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa" }; for (int i = 0; i < targets.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:PopClean.java
public static void main(String args[]) { try {//from w ww . j ava 2 s . c o m String hostname = null, username = null, password = null; int port = 110; int sizelimit = -1; String subjectPattern = null; Pattern pattern = null; Matcher matcher = null; boolean delete = false; boolean confirm = true; // Handle command-line arguments for (int i = 0; i < args.length; i++) { if (args[i].equals("-user")) username = args[++i]; else if (args[i].equals("-pass")) password = args[++i]; else if (args[i].equals("-host")) hostname = args[++i]; else if (args[i].equals("-port")) port = Integer.parseInt(args[++i]); else if (args[i].equals("-size")) sizelimit = Integer.parseInt(args[++i]); else if (args[i].equals("-subject")) subjectPattern = args[++i]; else if (args[i].equals("-debug")) debug = true; else if (args[i].equals("-delete")) delete = true; else if (args[i].equals("-force")) // don't confirm confirm = false; } // Verify them if (hostname == null || username == null || password == null || sizelimit == -1) usage(); // Make sure the pattern is a valid regexp if (subjectPattern != null) { pattern = Pattern.compile(subjectPattern); matcher = pattern.matcher(""); } // Say what we are going to do System.out .println("Connecting to " + hostname + " on port " + port + " with username " + username + "."); if (delete) { System.out.println("Will delete all messages longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } else { System.out.println("Will list subject lines for messages " + "longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } // If asked to delete, ask for confirmation unless -force is given if (delete && confirm) { System.out.println(); System.out.print("Do you want to proceed (y/n) [n]: "); System.out.flush(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); String response = console.readLine(); if (!response.equals("y")) { System.out.println("No messages deleted."); System.exit(0); } } // Connect to the server, and set up streams s = new Socket(hostname, port); in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); // Read the welcome message from the server, confirming it is OK. System.out.println("Connected: " + checkResponse()); // Now log in send("USER " + username); // Send username, wait for response send("PASS " + password); // Send password, wait for response System.out.println("Logged in"); // Check how many messages are waiting, and report it String stat = send("STAT"); StringTokenizer t = new StringTokenizer(stat); System.out.println(t.nextToken() + " messages in mailbox."); System.out.println("Total size: " + t.nextToken()); // Get a list of message numbers and sizes send("LIST"); // Send LIST command, wait for OK response. // Now read lines from the server until we get . by itself List msgs = new ArrayList(); String line; for (;;) { line = in.readLine(); if (line == null) throw new IOException("Unexpected EOF"); if (line.equals(".")) break; msgs.add(line); } // Now loop through the lines we read one at a time. // Each line should specify the message number and its size. int nummsgs = msgs.size(); for (int i = 0; i < nummsgs; i++) { String m = (String) msgs.get(i); StringTokenizer st = new StringTokenizer(m); int msgnum = Integer.parseInt(st.nextToken()); int msgsize = Integer.parseInt(st.nextToken()); // If the message is too small, ignore it. if (msgsize <= sizelimit) continue; // If we're listing messages, or matching subject lines // find the subject line for this message String subject = null; if (!delete || pattern != null) { subject = getSubject(msgnum); // get the subject line // If we couldn't find a subject, skip the message if (subject == null) continue; // If this subject does not match the pattern, then // skip the message if (pattern != null) { matcher.reset(subject); if (!matcher.matches()) continue; } // If we are listing, list this message if (!delete) { System.out.println("Subject " + msgnum + ": " + subject); continue; // so we never delete it } } // If we were asked to delete, then delete the message if (delete) { send("DELE " + msgnum); if (pattern == null) System.out.println("Deleted message " + msgnum); else System.out.println("Deleted message " + msgnum + ": " + subject); } } // When we're done, log out and shutdown the connection shutdown(); } catch (Exception e) { // If anything goes wrong print exception and show usage System.err.println(e); usage(); // Always try to shutdown nicely so the server doesn't hang on us shutdown(); } }
From source file:io.aos.protocol.http.httpcommon.ElementalHttpPost.java
public static void main(String... args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Test/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {// www . ja v a2 s.co m HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"), new ByteArrayEntity("This is the second test request".getBytes("UTF-8")), new InputStreamEntity(new ByteArrayInputStream( "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }