List of usage examples for java.net Socket Socket
public Socket(InetAddress address, int port) throws IOException
From source file:LCModels.MessageTransmitter.java
@Override public void run() { try {/* w w w. j a va 2 s . c o m*/ // Socket connects to the ServerSocket, ServerSocket receives a Socket, what? haha// //send data as points // Socket s = new Socket(hostname,targetPort); // Socket z = new Socket(hostname, 48500, InetAddress.getByName("127.0.0.1"), targetPort); Socket client = new Socket(hostname, targetPort); /* Get server's OutputStream */ OutputStream outToServer = client.getOutputStream(); /* Get server's DataOutputStream to write/send message */ DataOutputStream out = new DataOutputStream(outToServer); /* Write message to DataOutputStream */ out.writeUTF(transmitJSON.toString()); /* Get InputStream to get message from server */ InputStream inFromServer = client.getInputStream(); /* Get DataInputStream to read message of server */ DataInputStream in = new DataInputStream(inFromServer); /* Print message received from server */ System.out.println("Server says..." + in.readUTF()); client.close(); } catch (IOException ex) { Logger.getLogger(MessageTransmitter.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:net.aircable.aircam.SL4A.java
public void connect() throws UnknownHostException, IOException, JSONException { proxy = AndroidProxy.sProxy;//from ww w .j a v a 2 s . co m host = proxy.getAddress().getHostName(); port = proxy.getAddress().getPort(); secret = proxy.getSecret(); connection = new Socket(host, port); input = new BufferedReader(new InputStreamReader(connection.getInputStream(), "8859_1"), 1 << 13); output = new PrintWriter( new OutputStreamWriter(new BufferedOutputStream(connection.getOutputStream(), 1 << 13), "8859_1"), true); id = 0; if (this.secret != null) try { this.callMethod("_authenticate", new JSONArray('[' + this.secret + ']')); } catch (RuntimeException e) { if (!e.getMessage().contains("Unknown RPC")) throw e; } }
From source file:org.openbaton.vnfm.utils.Utils.java
public static boolean available(String ip, String port) { try {//ww w .j a v a 2s . co m Socket s = new Socket(ip, Integer.parseInt(port)); s.close(); return true; } catch (IOException ex) { // The remote host is not listening on this port return false; } }
From source file:de.tor.tribes.util.OBSTReportSender.java
public static void sendReport(URL pTarget, String pData) 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(pTarget.getHost(), pTarget.getPort()); 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 ava 2 s . c o m*/ HttpEntity[] requestBodies = { new StringEntity(pData) }; 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", pTarget.getPath() + "?" + pTarget.getQuery()); 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:com.mtnfog.idyl.e3.sdk.IdylE3StreamingClient.java
/** * Creates a new streaming client.//from w w w .jav a 2 s. co m * * @param server * The address of the Idyl E3 server. * @param port * The streaming port. * @throws UnknownHostException * Thrown if the host is invalid. * @throws IOException * Thrown if the socket connection cannot be opened. */ public IdylE3StreamingClient(String server, int port) throws UnknownHostException, IOException { socket = new Socket(server, port); gson = new Gson(); }
From source file:com.googlecode.jmxtrans.connections.SocketFactory.java
/** * Creates the socket and the writer to go with it. *//* www .j a va 2s. c o m*/ @Override public Socket makeObject(InetSocketAddress address) throws Exception { Socket socket = new Socket(address.getHostName(), address.getPort()); socket.setKeepAlive(true); return socket; }
From source file:com.symbian.utils.cmdline.argscheckers.OpenSocketData.java
/** {@inheritDoc} * @see com.symbian.utils.cmdline.argscheckers.DataAcceptable#check(java.lang.String) * @param aString {@inheritDoc}// ww w .j a v a 2 s. c o m * @throws ParseException {@inheritDoc} */ public void check(final String aString) throws ParseException { String[] lSplitSocket = aString.split(":"); if (lSplitSocket.length < 1 || lSplitSocket.length > 2) { throw new ParseException("illegal socket name"); } int lPort = (lSplitSocket.length == 1) ? DEFAULT_PORT : Integer.parseInt(lSplitSocket[1]); if (lPort == 0) { throw new ParseException("illegal port number"); } String lServer = lSplitSocket[0]; Socket lSocket = null; // connect to server try { lSocket = new Socket(lServer, lPort); lSocket.close(); lSocket = null; } catch (Exception lException) { throw new ParseException("cannot connect to socket '" + aString + "'"); } }
From source file:com.esri.geoevent.test.performance.tcp.TcpEventConsumer.java
@Override public synchronized void init(Config config) throws TestException { try {//from www . j a v a 2 s .c om super.init(config); host = config.getPropertyValue("hosts", "localhost"); //if we have list, then grab the first one if (host.indexOf(",") != -1) { host = host.split(",")[0]; } port = Integer.parseInt(config.getPropertyValue("port", "5570")); socket = new Socket(host, port); socket.setSoTimeout(50); is = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (Throwable error) { throw new TestException( ImplMessages.getMessage("INIT_FAILURE", getClass().getName(), error.getMessage()), error); } }
From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java
public void send(String server, Integer port, Long numEvents, Integer rate) { Random rnd = new Random(); BufferedReader br = null;/*from w w w . j a v a2s. c om*/ LocalDateTime st = null; try { Socket sckt = new Socket(server, port); OutputStream os = sckt.getOutputStream(); //PrintWriter sckt_out = new PrintWriter(os, true); Integer cnt = 0; st = LocalDateTime.now(); Double ns_delay = 1000000000.0 / (double) rate; long ns = ns_delay.longValue(); if (ns < 0) { ns = 0; } while (cnt < numEvents) { cnt += 1; LocalDateTime ct = LocalDateTime.now(); String dtg = ct.toString(); Double lat = 180 * rnd.nextDouble() - 90.0; Double lon = 360 * rnd.nextDouble() - 180.0; String line = "RandomPoint," + cnt.toString() + "," + dtg + ",\"" + lon.toString() + "," + lat.toString() + "\"," + cnt.toString() + "\n"; final long stime = System.nanoTime(); long etime = 0; do { etime = System.nanoTime(); } while (stime + ns >= etime); if (cnt % 1000 == 0) { //System.out.println(cnt); } //sckt_out.write(line); os.write(line.getBytes()); os.flush(); } if (st != null) { LocalDateTime et = LocalDateTime.now(); Duration delta = Duration.between(st, et); Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0; send_rate = (double) numEvents / elapsed_seconds; } //sckt_out.close(); sckt.close(); os = null; //sckt_out = null; } catch (Exception e) { System.err.println(e.getMessage()); send_rate = -1.0; } finally { try { br.close(); } catch (Exception e) { // } this.send_rate = send_rate; } }
From source file:de.alexkamp.sandbox.ChrootSandbox.java
public ChrootSandbox(JsonFactory factory, String host, int port, SandboxData data) { this.factory = new JsonFactory(); this.data = data; try {/*ww w .j a v a2s . c om*/ socket = new Socket(host, port); this.sender = factory.createGenerator(socket.getOutputStream()); } catch (IOException ex) { throw new SandboxException(ex); } this.reader = new Thread(this); this.reader.start(); try { connect(); } catch (IOException ex) { throw new SandboxException(ex); } }