List of usage examples for java.net Socket getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:TcpClient.java
/** Default constructor. */ public TcpServer() { this.payload = new TcpPayload(); initServerSocket();/*from w ww.java2 s . c o m*/ try { while (true) { // listen for and accept a client connection to serverSocket Socket sock = this.serverSocket.accept(); OutputStream oStream = sock.getOutputStream(); ObjectOutputStream ooStream = new ObjectOutputStream(oStream); ooStream.writeObject(this.payload); // send serilized payload ooStream.close(); Thread.sleep(1000); } } catch (SecurityException se) { System.err.println("Unable to get host address due to security."); System.err.println(se.toString()); System.exit(1); } catch (IOException ioe) { System.err.println("Unable to read data from an open socket."); System.err.println(ioe.toString()); System.exit(1); } catch (InterruptedException ie) { } // Thread sleep interrupted finally { try { this.serverSocket.close(); } catch (IOException ioe) { System.err.println("Unable to close an open socket."); System.err.println(ioe.toString()); System.exit(1); } } }
From source file:SmtpTalk.java
/** * Constructor taking a server hostname as argument. *///from w w w. ja va 2 s. co m SmtpTalk(String server) throws Exception { host = server; try { Socket s = new Socket(host, 25); is = new BufferedReader(new InputStreamReader(s.getInputStream())); os = new PrintStream(s.getOutputStream()); } catch (NoRouteToHostException e) { die("No route to host " + host); } catch (ConnectException e) { die("Connection Refused by " + host); } catch (UnknownHostException e) { die("Unknown host " + host); } catch (IOException e) { die("I/O error setting up socket streams\n" + e); } }
From source file:pl.edu.agh.ServiceConnection.java
/** * 1. Sends data to service: console password | service password | service id *//* w w w.j a v a2 s.c o m*/ public void connect(Service service) { try { LOGGER.info("Connecting to service: " + service); Socket socket = new Socket(service.getHost(), service.getPort()); socket.setSoTimeout(300); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.writeBytes(service.getPassword() + "|" + service.getId() + "\r\n"); String response = in.readLine(); in.close(); out.close(); socket.close(); LOGGER.info("Service response: " + response); } catch (Exception e) { LOGGER.error("Error connecting with daemon: " + e.getMessage()); } }
From source file:epn.edu.ec.bibliotecadigital.servidor.ServerRunnable.java
private void actualizarLibrosEnServidores(String fileName) { try {/* w ww. ja v a 2s.c o m*/ Socket socket = new Socket("192.168.100.14", 8888); DataOutputStream dataOut = new DataOutputStream(socket.getOutputStream()); dataOut.writeUTF("actualizar"); dataOut.writeUTF("servidor"); dataOut.writeUTF(fileName); OutputStream out = socket.getOutputStream(); try { byte[] bytes = new byte[64 * 1024]; InputStream in = new FileInputStream("C:\\Computacion Distribuida\\" + fileName); int count; while ((count = in.read(bytes)) > 0) { out.write(bytes, 0, count); } in.close(); } finally { IOUtils.closeQuietly(out); } } catch (IOException ex) { Logger.getLogger(ServerRunnable.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.google.dataconnector.util.Rfc1929SdcAuthenticator.java
/** * Reads the authentication data from the session and validates request * //from w w w. jav a2 s. c o m * @param s connected socket from incoming SOCKS client. * @throws IOException if there are any socket communication issues. */ @Override public ServerAuthenticator startSession(final Socket s) throws IOException { final InputStream in = s.getInputStream(); final OutputStream out = s.getOutputStream(); if (in.read() != 5) { // Drop non version 5 messages. return null; } if (!selectSocks5Authentication(in, out, METHOD_ID)) return null; if (!doUserPasswordAuthentication(s, in, out)) return null; return new Rfc1929SdcAuthenticator(in, out, passKey, keyManager, serverMetaData); }
From source file:org.jmxtrans.embedded.samples.graphite.GraphiteDataInjector.java
public void exportMetrics(TimeSeries timeSeries) throws IOException { System.out.println("Export '" + timeSeries.getKey() + "' to " + graphiteHost + " with prefix '" + graphiteMetricPrefix + "'"); Socket socket = new Socket(graphiteHost, graphitePort); OutputStream outputStream = socket.getOutputStream(); if (generateDataPointsFile) { JFreeChart chart = ChartFactory.createXYLineChart("Purchase", "date", "Amount", new TimeSeriesCollection(timeSeries), PlotOrientation.VERTICAL, true, true, false); // chart.getXYPlot().setRenderer(new XYSplineRenderer(60)); File file = new File("/tmp/" + timeSeries.getKey() + ".png"); ChartUtilities.saveChartAsPNG(file, chart, 1200, 800); System.out.println("Exported " + file.getAbsolutePath()); String pickleFileName = "/tmp/" + timeSeries.getKey().toString() + ".pickle"; System.out.println("Generate " + pickleFileName); outputStream = new TeeOutputStream(outputStream, new FileOutputStream(pickleFileName)); }/*from w ww. j a v a2s.c om*/ PyList list = new PyList(); for (int i = 0; i < timeSeries.getItemCount(); i++) { if (debug) System.out.println(new DateTime(timeSeries.getDataItem(i).getPeriod().getStart()) + "\t" + timeSeries.getDataItem(i).getValue().intValue()); String metricName = graphiteMetricPrefix + timeSeries.getKey().toString(); int time = (int) TimeUnit.SECONDS.convert(timeSeries.getDataItem(i).getPeriod().getStart().getTime(), TimeUnit.MILLISECONDS); int value = timeSeries.getDataItem(i).getValue().intValue(); list.add(new PyTuple(new PyString(metricName), new PyTuple(new PyInteger(time), new PyInteger(value)))); if (list.size() >= batchSize) { System.out.print("-"); rateLimiter.acquire(list.size()); sendDataPoints(outputStream, list); } } // send last data points if (!list.isEmpty()) { rateLimiter.acquire(list.size()); sendDataPoints(outputStream, list); } Flushables.flushQuietly(outputStream); Closeables.close(outputStream, true); try { socket.close(); } catch (Exception e) { // swallow exception e.printStackTrace(); } System.out.println(); System.out.println("Exported " + timeSeries.getKey() + ": " + timeSeries.getItemCount() + " items"); }
From source file:com.sixt.service.framework.servicetest.mockservice.MockHttpServletResponse.java
public MockHttpServletResponse(Socket socket) throws IOException { this.socket = socket; writer = new HttpResponseWriter(this, socket.getOutputStream()); }
From source file:bankingclient.TaoTaiKhoanFrame.java
public TaoTaiKhoanFrame(NewOrOldAccFrame acc) { initComponents();//from ww w . j av a 2s . c o m this.jText_ten_tk.setText(""); this.jText_sd.setText(""); this.noAcc = acc; this.mainCustomerName = null; this.setVisible(false); jBt_ht.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (NumberUtils.isNumber(jText_sd.getText()) && (Long.parseLong(jText_sd.getText()) > 0)) { try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(3); dout.writeUTF(jText_ten_tk.getText() + "\n" + mainCustomerName + "\n" + jText_sd.getText()); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); byte check = din.readByte(); if (check == 1) { JOptionPane.showMessageDialog(rootPane, "da tao tai khoan thanh cong"); } else { JOptionPane.showMessageDialog(rootPane, "tao tai khoan khong thanh cong"); } client.close(); } catch (Exception ex) { ex.printStackTrace(); } noAcc.setVisible(true); TaoTaiKhoanFrame.this.setVisible(false); } else { JOptionPane.showMessageDialog(rootPane, "Can nhap lai so tien gui"); } } }); jBt_ql.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { noAcc.setVisible(true); TaoTaiKhoanFrame.this.setVisible(false); } }); }
From source file:org.freewheelschedule.freewheel.controlserver.ControlThread.java
private void runJob(String hostname, Job jobToRun) throws IOException { log.debug("Connecting to the RemoteWorker to run a command"); Socket remoteWorker = new Socket(jobToRun.getExecutingServer().getName(), jobToRun.getExecutingServer().getPort().intValue()); PrintWriter command = new PrintWriter(remoteWorker.getOutputStream(), true); BufferedReader result = new BufferedReader(new InputStreamReader(remoteWorker.getInputStream())); if (workerAwaitingCommand(result, command, hostname) && jobToRun instanceof CommandJob) { if (!sendCommandToExecute(jobToRun, result, command)) { log.error("Job not queued properly"); } else {//from w w w .jav a2 s . c o m log.error("Unexpected response from RemoteClient"); } } }
From source file:com.bitsofproof.supernode.core.IRCDiscovery.java
@Override public List<InetSocketAddress> discover() { List<InetSocketAddress> al = new ArrayList<InetSocketAddress>(); try {/*from w w w.ja v a2s . c o m*/ log.trace("Connect to IRC server " + server); Socket socket = new Socket(server, port); PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); String[] answers = new String[] { "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname" }; String line; boolean stop = false; while (!stop && (line = reader.readLine()) != null) { log.trace("IRC receive " + line); for (int i = 0; i < answers.length; ++i) { if (line.contains(answers[i])) { stop = true; break; } } } String nick = "bop" + new SecureRandom().nextInt(Integer.MAX_VALUE); writer.println("NICK " + nick); writer.println("USER " + nick + " 8 * : " + nick); writer.flush(); log.trace("IRC send: I am " + nick); while ((line = reader.readLine()) != null) { log.trace("IRC receive " + line); if (hasCode(line, new String[] { " 004 ", " 433 " })) { break; } } log.trace("IRC send: joining " + channel); writer.println("JOIN " + channel); writer.println("NAMES"); writer.flush(); while ((line = reader.readLine()) != null) { log.trace("IRC receive " + line); if (hasCode(line, new String[] { " 353 " })) { StringTokenizer tokenizer = new StringTokenizer(line, ":"); String t = tokenizer.nextToken(); if (tokenizer.hasMoreElements()) { t = tokenizer.nextToken(); } tokenizer = new StringTokenizer(t); tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { String w = tokenizer.nextToken().substring(1); if (!tokenizer.hasMoreElements()) { continue; } try { byte[] m = ByteUtils.fromBase58WithChecksum(w); byte[] addr = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff, 0, 0, 0, 0 }; System.arraycopy(m, 0, addr, 12, 4); al.add(new InetSocketAddress(InetAddress.getByAddress(addr), chain.getPort())); } catch (ValidationException e) { log.trace(e.toString()); } } } if (hasCode(line, new String[] { " 366 " })) { break; } } writer.println("PART " + channel); writer.println("QUIT"); writer.flush(); socket.close(); } catch (UnknownHostException e) { log.error("Can not find IRC server " + server, e); } catch (IOException e) { log.error("Can not use IRC server " + server, e); } return al; }