List of usage examples for java.net Socket getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.raddle.tools.ClipboardTransferMain.java
private void setRemoteClipboard(boolean alert) { if (!isProcessing) { isProcessing = true;// www . ja v a 2 s.com try { Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable clipT = sysc.getContents(null); if (alert && !ClipboardUtils.isClipboardNotEmpty(clipT)) { updateMessage("?"); return; } updateMessage("???"); trayIcon.setImage(sendImage); final BooleanHolder success = new BooleanHolder(); doInSocket(new SocketCallback() { @Override public Object connected(Socket socket) throws Exception { ClipCommand cmd = new ClipCommand(); cmd.setCmdCode(ClipCommand.CMD_SET_CLIP); cmd.setResult(ClipboardUtils.getClipResult()); // ?? ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); out.writeObject(cmd); // ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); ClipResult result = (ClipResult) in.readObject(); if (result.isSuccess()) { StringBuilder sb = new StringBuilder(); for (DataFlavor dataFlavor : cmd.getResult().getClipdata().keySet()) { sb.append("\n"); sb.append(dataFlavor.getPrimaryType()).append("/").append(dataFlavor.getSubType()); } iconQueue.add("send"); success.value = true; updateMessage("????? " + sb); } else { updateMessage("???:" + result.getMessage()); } in.close(); out.close(); return null; } }); if (!success.value) { trayIcon.setImage(grayImage); } } catch (Exception e) { trayIcon.setImage(grayImage); updateMessage("???" + e.getMessage()); } finally { isProcessing = false; } } }
From source file:com.t_oster.liblasercut.drivers.LaosCutter.java
@Override public void sendJob(LaserJob job, ProgressListener pl, List<String> warnings) throws IllegalJobException, Exception { currentFrequency = -1;//from ww w.j a v a 2 s . com currentPower = -1; currentSpeed = -1; currentFocus = 0; currentPurge = false; currentVentilation = false; pl.progressChanged(this, 0); BufferedOutputStream out; ByteArrayOutputStream buffer = null; pl.taskChanged(this, "checking job"); checkJob(job); job.applyStartPoint(); if (!useTftp) { pl.taskChanged(this, "connecting"); Socket connection = new Socket(); connection.connect(new InetSocketAddress(hostname, port), 3000); out = new BufferedOutputStream(connection.getOutputStream()); pl.taskChanged(this, "sending"); } else { buffer = new ByteArrayOutputStream(); out = new BufferedOutputStream(buffer); pl.taskChanged(this, "buffering"); } this.writeJobCode(job, out, pl); if (this.isUseTftp()) { pl.taskChanged(this, "connecting"); TFTPClient tftp = new TFTPClient(); tftp.setDefaultTimeout(5000); //open a local UDP socket tftp.open(); pl.taskChanged(this, "sending"); ByteArrayInputStream bain = new ByteArrayInputStream(buffer.toByteArray()); tftp.sendFile(job.getName().replace(" ", "") + ".lgc", TFTP.BINARY_MODE, bain, this.getHostname(), this.getPort()); tftp.close(); bain.close(); if (debugFilename != null && !"".equals(debugFilename)) { pl.taskChanged(this, "writing " + debugFilename); FileOutputStream o = new FileOutputStream(new File(debugFilename)); o.write(buffer.toByteArray()); o.close(); } pl.taskChanged(this, "sent."); } pl.progressChanged(this, 100); }
From source file:com.apporiented.hermesftp.client.FtpTestClient.java
private void initializeIOStreams() throws IOException { if (passiveModeSocket != null) { transIs = passiveModeSocket.getInputStream(); transOut = passiveModeSocket.getOutputStream(); } else if (activeModeServerSocket != null) { Socket socket = activeModeServerSocket.accept(); transIs = socket.getInputStream(); transOut = socket.getOutputStream(); } else {//www .j av a2s .c om throw new IOException("IO streams have not been initialized"); } }
From source file:com.jayway.maven.plugins.android.AbstractEmulatorMojo.java
/** * Sends a user command to the running emulator via its telnet interface. * * @param port The emulator's telnet port. * @param command The command to execute on the emulator's telnet interface. * @return Whether sending the command succeeded. *//*w w w . j a va 2 s .c om*/ private boolean sendEmulatorCommand( //final Launcher launcher, //final PrintStream logger, final int port, final String command) { Callable<Boolean> task = new Callable<Boolean>() { public Boolean call() throws IOException { Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket("127.0.0.1", port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (in.readLine() == null) { return false; } out.write(command); out.write("\r\n"); } finally { try { out.close(); in.close(); socket.close(); } catch (Exception e) { // Do nothing } } return true; } private static final long serialVersionUID = 1L; }; boolean result = false; try { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Boolean> future = executor.submit(task); result = future.get(); } catch (Exception e) { getLog().error(String.format("Failed to execute emulator command '%s': %s", command, e)); } return result; }
From source file:net.demilich.metastone.bahaviour.ModifiedMCTS.MCTSCritique.java
public void sendCaffeData(double[][] data2, double[][] labels2, double[][] weights, String name, boolean ordered, boolean file) { double[][] data = new double[data2.length][]; double[][] labels = new double[data2.length][]; if (!ordered) { for (int i = 0; i < data2.length; i++) { data[i] = data2[i].clone();// ww w . j av a 2 s . c om labels[i] = labels2[i].clone(); } } else { data = data2; labels = labels2; } try { String sentence; String modifiedSentence; Random generator = new Random(); //set up our socket server BufferedReader inFromServer = null; DataOutputStream outToServer = null; Socket clientSocket = null; //add in data in a random order if (!file) { System.err.println("starting to send on socket"); clientSocket = new Socket("localhost", 5004); clientSocket.setTcpNoDelay(false); outToServer = new DataOutputStream(clientSocket.getOutputStream()); inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); outToServer.writeBytes(name + "\n"); outToServer.writeBytes((data.length + " " + data[0].length + " " + labels[0].length) + "\n"); try { Thread.sleep(10000); } catch (Exception e) { } } else { outToServer = new DataOutputStream((OutputStream) new FileOutputStream(name)); } StringBuffer wholeMessage = new StringBuffer(); for (int i = 0; i < data.length; i++) { if (i % 1000 == 0) { System.err.println("(constructed) i is " + i); } String features = ""; int randomIndex = generator.nextInt(data.length - i); if (!ordered) { swap(data, i, i + randomIndex); swap(labels, i, i + randomIndex); } for (int a = 0; a < data[i].length; a++) { wholeMessage.append(data[i][a] + " "); } wholeMessage.append("\n"); String myLabels = ""; for (int a = 0; a < labels[i].length; a++) { wholeMessage.append(labels[i][a] + " "); } wholeMessage.append("\n"); wholeMessage.append(weights[i][0] + ""); wholeMessage.append("\n"); outToServer.writeBytes(wholeMessage.toString()); wholeMessage = new StringBuffer(); } System.err.println("total message size is " + wholeMessage.toString().length()); //outToServer.writeBytes(wholeMessage.toString()); if (!file) { System.err.println("sending done"); outToServer.writeBytes("done\n"); System.err.println("waiting for ack..."); inFromServer.readLine(); System.err.println("got the ack!"); clientSocket.close(); } } catch (Exception e) { e.printStackTrace(); System.err.println("server wasn't waiting"); } System.err.println("hey i sent somethin!"); }
From source file:Network.CReportHandler.java
@Override public void update(Observable o, Object arg) { Socket objSocket = (Socket) arg; int intSeq = -1; try {/* w w w. j a va 2s. c o m*/ System.out.println("dasdasdasdsa"); /* JSONParser jsonParser = new JSONParser(); JSONObject objJSON = (JSONObject) jsonParser.parse(new InputStreamReader(objSocket.getInputStream())); System.out.println(objJSON.toJSONString()); int intTempSeq = Integer.parseInt(objJSON.get("id").toString()); CReport.genReport((JSONArray) objJSON.get("stats")); intSeq = intTempSeq;*/ // } catch (IOException | ParseException | NumberFormatException | COSVisitorException ex) { // System.out.println(ex); } finally { try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()), StandardCharsets.US_ASCII.name())) { objWriter.write(intSeq + ""); objWriter.flush(); } catch (IOException ex) { System.out.println(ex); } } }
From source file:com.android.development.Connectivity.java
private void onBoundSocketRequest() { NetworkInterface networkInterface = null; try {//from ww w . j a va2 s. co m networkInterface = NetworkInterface.getByName("rmnet0"); } catch (Exception e) { Log.e(TAG, "exception getByName: " + e); return; } if (networkInterface == null) { try { Log.d(TAG, "getting any networkInterface"); networkInterface = NetworkInterface.getNetworkInterfaces().nextElement(); } catch (Exception e) { Log.e(TAG, "exception getting any networkInterface: " + e); return; } } if (networkInterface == null) { Log.e(TAG, "couldn't find a local interface"); return; } Enumeration inetAddressess = networkInterface.getInetAddresses(); while (inetAddressess.hasMoreElements()) { Log.d(TAG, " addr:" + ((InetAddress) inetAddressess.nextElement())); } InetAddress local = null; InetAddress remote = null; try { local = networkInterface.getInetAddresses().nextElement(); } catch (Exception e) { Log.e(TAG, "exception getting local InetAddress: " + e); return; } try { remote = InetAddress.getByName("www.flickr.com"); } catch (Exception e) { Log.e(TAG, "exception getting remote InetAddress: " + e); return; } Log.d(TAG, "remote addr =" + remote); Log.d(TAG, "local addr =" + local); Socket socket = null; try { socket = new Socket(remote, 80, local, 6000); } catch (Exception e) { Log.e(TAG, "Exception creating socket: " + e); return; } try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("Hi flickr"); } catch (Exception e) { Log.e(TAG, "Exception writing to socket: " + e); return; } }
From source file:com.nohkumado.ipx800control.Ipx800Control.java
/** sendCmd/* w w w .j a va 2 s . c o m*/ @param cmd the command to send opens a TCP port and sends a m2m command to the ipx, stores the eventual result in return in @see returnMsg */ protected boolean sendCmd(String cmd) { Socket socket = null; PrintWriter out = null; BufferedReader in = null; //System.out.println("sendcmd for "+cmd); try { //System.out.println("opening "+server+":"+port); socket = new Socket(server, port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //System.out.println("about to send out cmd"); out.println(cmd); //System.out.println("waiting for return"); returnMsg = in.readLine(); //System.out.println("return from ipx:"+returnMsg); if (returnMsg.matches("=")) { String[] parts = returnMsg.split("="); //String part1 = parts[0]; // Getin returnMsg = parts[1]; // value } out.close(); in.close(); socket.close(); } catch (UnknownHostException e) { System.err.println("Don't know about host " + server); return false; } catch (IOException e) { System.err.println("Couldn't get I/O for the connection"); return false; } return true; }
From source file:com.cws.esolutions.core.utils.NetworkUtils.java
/** * Creates an telnet connection to a target host and port number. Silently * succeeds if no issues are encountered, if so, exceptions are logged and * re-thrown back to the requestor.//w w w . jav a 2 s. c om * * If an exception is thrown during the <code>socket.close()</code> operation, * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate * a connection failure (indeed, it means the connection succeeded) but it is * logged because continued failures to close the socket could result in target * system instability. * * @param hostName - The target host to make the connection to * @param portNumber - The port number to attempt the connection on * @param timeout - The timeout for the connection * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing */ public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException { final String methodName = NetworkUtils.CNAME + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug(hostName); DEBUGGER.debug("portNumber: {}", portNumber); DEBUGGER.debug("timeout: {}", timeout); } Socket socket = null; try { synchronized (new Object()) { if (InetAddress.getByName(hostName) == null) { throw new UnknownHostException("No host was found in DNS for the given name: " + hostName); } InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber); socket = new Socket(); socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout)); socket.setSoLinger(false, 0); socket.setKeepAlive(false); socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout)); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF); pWriter.flush(); pWriter.close(); } } catch (ConnectException cx) { throw new UtilityException(cx.getMessage(), cx); } catch (UnknownHostException ux) { throw new UtilityException(ux.getMessage(), ux); } catch (SocketException sx) { throw new UtilityException(sx.getMessage(), sx); } catch (IOException iox) { throw new UtilityException(iox.getMessage(), iox); } finally { try { if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { // log it - this could cause problems later on ERROR_RECORDER.error(iox.getMessage(), iox); } } }
From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java
/** * Send a TCP request/*from w ww.ja v a 2s. c om*/ * @param socket Socket to write to * @param request Request to send * @throws ApiException */ private void sendTcpRequest(Socket socket, String request) throws ApiException { try { LogUtils.LOGD(TAG, "Sending request via TCP: " + request); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); writer.write(request); writer.flush(); } catch (Exception e) { LogUtils.LOGW(TAG, "Failed to send TCP request.", e); disconnect(); throw new ApiException(ApiException.IO_EXCEPTION_WHILE_SENDING_REQUEST, e); } }