List of usage examples for java.net Socket getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.example.blackberry.agoodandroidsample.SocketFragment.java
/** * Creates a socket connection to developer.BlackBerry.com:80. * @return An InputStream retrieved from a successful HttpURLConnection. * @throws java.io.IOException/* w w w. jav a 2 s .c om*/ */ private String doSocket() throws IOException { Socket socket = null; InputStream inputStream = null; OutputStream outputStream = null; try { socket = new Socket("developer.blackberry.com", 80); String response = ""; //We'll make an HTTP request over the socket connection. String output = "GET http://developer.blackberry.com/ HTTP/1.1\r\n" + "Host: developer.blackberry.com:80\r\n" + "Connection: close\r\n" + "\r\n"; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int bytesRead; inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); outputStream.write(output.getBytes()); while ((bytesRead = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); response += byteArrayOutputStream.toString("UTF-8"); if (response.length() > 1000) { //Stop reading after we've reached 1000 characters. break; } } //Close all connections. inputStream.close(); outputStream.close(); byteArrayOutputStream.close(); return response; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } if (socket != null) { socket.close(); } } }
From source file:mamo.vanillaVotifier.VotifierServer.java
public synchronized void start() throws IOException { if (isRunning()) { throw new IllegalStateException("Server is already running!"); }//from w w w . j a v a2s . co m notifyListeners(new ServerStartingEvent()); serverSocket = new ServerSocket(); serverSocket.bind(votifier.getConfig().getInetSocketAddress()); running = true; notifyListeners(new ServerStartedEvent()); new Thread(new Runnable() { @Override public void run() { ExecutorService executorService = Executors.newSingleThreadExecutor(); while (isRunning()) { try { final Socket socket = serverSocket.accept(); executorService.execute(new Runnable() { @Override public void run() { try { notifyListeners(new ConnectionEstablishedEvent(socket)); socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch. BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); writer.write("VOTIFIER 2.9\n"); writer.flush(); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch. byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair() .getPublic()).getModulus().bitLength() / Byte.SIZE]; in.read(request); // IOException: handled by try/catch. notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request))); request = RsaUtils .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate()) .doFinal(request); // IllegalBlockSizeException: can't happen. String requestString = new String(request); notifyListeners(new DecryptedInputReceivedEvent(socket, requestString)); String[] requestArray = requestString.split("\n"); if ((requestArray.length == 5 || requestArray.length == 6) && requestArray[0].equals("VOTE")) { notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1], requestArray[2], requestArray[3], requestArray[4]))); for (VoteAction voteAction : votifier.getConfig().getVoteActions()) { String[] params = new String[4]; try { for (int i = 0; i < params.length; i++) { params[i] = SubstitutionUtils.applyRegexReplacements( requestArray[i + 1], voteAction.getRegexReplacements()); } } catch (PatternSyntaxException e) { notifyListeners(new RegularExpressionPatternErrorException(e)); params = new String[] { requestArray[1], requestArray[2], requestArray[3], requestArray[4] }; } if (voteAction.getCommandSender() instanceof RconCommandSender) { RconCommandSender commandSender = (RconCommandSender) voteAction .getCommandSender(); StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor( new SimpleEntry<String, Object>("service-name", params[0]), new SimpleEntry<String, Object>("user-name", params[1]), new SimpleEntry<String, Object>("address", params[2]), new SimpleEntry<String, Object>("timestamp", params[3])); for (String command : voteAction.getCommands()) { String theCommand = substitutor.replace(command); notifyListeners(new SendingRconCommandEvent( commandSender.getRconConnection(), theCommand)); try { notifyListeners(new RconCommandResponseEvent( commandSender.getRconConnection(), commandSender .sendCommand(theCommand).getPayload())); } catch (Exception e) { notifyListeners(new RconExceptionEvent( commandSender.getRconConnection(), e)); } } } if (voteAction.getCommandSender() instanceof ShellCommandSender) { ShellCommandSender commandSender = (ShellCommandSender) voteAction .getCommandSender(); HashMap<String, String> environment = new HashMap<String, String>(); environment.put("voteServiceName", params[0]); environment.put("voteUserName", params[1]); environment.put("voteAddress", params[2]); environment.put("voteTimestamp", params[3]); for (String command : voteAction.getCommands()) { notifyListeners(new SendingShellCommandEvent(command)); try { commandSender.sendCommand(command, environment); notifyListeners(new ShellCommandSentEvent()); } catch (Exception e) { notifyListeners(new ShellCommandExceptionEvent(e)); } } } } } else { notifyListeners(new InvalidRequestEvent(socket, requestString)); } } catch (SocketTimeoutException e) { notifyListeners(new ReadTimedOutExceptionEvent(socket, e)); } catch (BadPaddingException e) { notifyListeners(new DecryptInputExceptionEvent(socket, e)); } catch (Exception e) { notifyListeners(new CommunicationExceptionEvent(socket, e)); } try { socket.close(); notifyListeners(new ConnectionClosedEvent(socket)); } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close. notifyListeners(new ConnectionCloseExceptionEvent(socket, e)); } } }); } catch (Exception e) { if (running) { // Show errors only while running, to hide error while stopping. notifyListeners(new ConnectionEstablishExceptionEvent(e)); } } } executorService.shutdown(); if (!executorService.isTerminated()) { notifyListeners(new ServerAwaitingTaskCompletionEvent()); try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (Exception e) { // InterruptedException: can't happen. } } notifyListeners(new ServerStoppedEvent()); } }).start(); }
From source file:com.clustercontrol.notify.util.SendSyslog.java
private void sendTcpMsg(InetAddress ipAddress, int port, String msg) throws IOException { Socket socket = null; OutputStream os = null;// w w w. j a v a 2 s . c o m PrintWriter writer = null; try { InetSocketAddress endpoint = new InetSocketAddress(ipAddress, port); socket = new Socket(); socket.connect(endpoint, HinemosPropertyUtil.getHinemosPropertyNum(PROP_TCP_TIMEOUT, Long.valueOf(3000)).intValue()); os = socket.getOutputStream(); writer = new PrintWriter(socket.getOutputStream(), true); writer.println(msg); writer.flush(); } finally { if (writer != null) { writer.close(); } if (os != null) { os.close(); } if (socket != null) { socket.close(); } } }
From source file:com.mirth.connect.connectors.tcp.TcpMessageDispatcher.java
protected void write(Socket socket, String data) throws Exception { byte[] buffer = null; // When working with binary data the template has to be base64 encoded if (connector.isBinary()) { buffer = Base64.decodeBase64(data); } else {//from w w w . j av a 2 s . c o m buffer = data.getBytes(connector.getCharsetEncoding()); } TcpProtocol protocol = connector.getTcpProtocol(); BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream()); protocol.write(bos, buffer); bos.flush(); }
From source file:com.clavain.munin.MuninNode.java
private void updateEssentials(Socket p_socket) { String decodestr = ""; try {/* w ww . j a v a 2 s .c o m*/ PrintStream os = new PrintStream(p_socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(p_socket.getInputStream())); os.println("config muninmx_essentials"); // skip first line if starts with # decodestr = in.readLine(); if (decodestr.startsWith("#")) { decodestr = in.readLine(); } if (decodestr.equals(".")) { decodestr = in.readLine(); } BasicDBObject doc = new BasicDBObject(); doc.put("data", decodestr); doc.put("time", getUnixtime()); doc.put("node", this.node_id); doc.put("type", "essential"); com.clavain.muninmxcd.mongo_essential_queue.add(doc); logger.info("Essentials Updated for Node: " + this.getHostname() + ": received base64 (length): " + decodestr.length()); last_essentials_update = getUnixtime(); // read following . in.readLine(); } catch (Exception ex) { logger.error( "Error in updateEssentials for Node " + this.getHostname() + " : " + ex.getLocalizedMessage()); logger.error("updateEssentials for Node " + this.getHostname() + " received: " + decodestr); ex.printStackTrace(); } }
From source file:bankingclient.ChonThaoTacFrame.java
public ChonThaoTacFrame(NewOrOldAccFrame acc) { initComponents();//from w w w . ja va2 s . c om jTextField1.setText(""); jLabel4.setVisible(false); jComboBox2.setVisible(false); jLabel2.setVisible(false); jLabel3.setVisible(false); jTextField1.setVisible(false); jBt_xn1.setVisible(false); jBt_xn2.setVisible(false); this.accList = null; this.cusList = null; this.noAcc = acc; this.tt = new Thong_Tin_TK(this); this.setVisible(false); jBt_xn1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (NumberUtils.isNumber(jTextField1.getText()) && (Long.parseLong(jTextField1.getText()) > 0)) { long currentMoney = 0; try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(8); dout.writeUTF((String) jComboBox1.getSelectedItem()); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); Scanner lineScanner = new Scanner(din.readUTF()); currentMoney = Long.parseLong(lineScanner.nextLine()); System.out.println(currentMoney); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "Li kt ni mng,bn cn kim tra kt ni"); } if (jCheck_gt.isSelected()) { try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(5); dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + jTextField1.getText() + "\n" + (noAcc.getCustomer())); dout.flush(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy ra...."); } JOptionPane.showMessageDialog(rootPane, "Gi Ti?n Thnh Cng..."); } if (jCheck_rt.isSelected()) { if ((Long.parseLong(jTextField1.getText()) <= currentMoney)) { try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(6); dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + jTextField1.getText() + "\n" + (noAcc.getCustomer())); dout.flush(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy Ra....."); } JOptionPane.showMessageDialog(rootPane, "Rt Ti?n Thnh Cng ..."); } else { System.out.println("Khng Ti?n Trong ti khon.." + currentMoney); JOptionPane.showMessageDialog(null, "Ti Khon Khng ? ? Rt ..."); } } noAcc.setVisible(true); ChonThaoTacFrame.this.setVisible(false); } else { JOptionPane.showMessageDialog(rootPane, "Cn Nhp Li S Ti?n Cn Gi Hoc Rt.."); } } }); jBt_tt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tt.setTk((String) jComboBox1.getSelectedItem()); tt.hienTenTk(); long currentMoney = 0; try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(8); dout.writeUTF((String) jComboBox1.getSelectedItem()); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); Scanner lineScanner = new Scanner(din.readUTF()); currentMoney = Long.parseLong(lineScanner.nextLine()); // System.out.println(currentMoney); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "Li kt ni mng,bn cn kim tra kt ni"); } tt.hienSoDu(((Long) currentMoney).toString()); tt.setVisible(true); try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(10); dout.writeUTF((String) jComboBox1.getSelectedItem()); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); Scanner cusScanner = new Scanner(din.readUTF()); while (cusScanner.hasNextLine()) { tt.addCus(cusScanner.nextLine()); } } catch (Exception ee) { ee.printStackTrace(); } tt.hienChuTaiKhoan(); try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(12); dout.writeUTF((String) jComboBox1.getSelectedItem()); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); Scanner dateScanner = new Scanner(din.readUTF()); int day = Integer.parseInt(dateScanner.nextLine()); int month = Integer.parseInt(dateScanner.nextLine()); int year = Integer.parseInt(dateScanner.nextLine()); String date = (day + "-" + month + "-" + year); tt.hienNgayLapTaiKhoan(date); while (dateScanner.hasNextLine()) { // System.out.println("aaa"); tt.addGiaoDich(dateScanner.nextLine()); } tt.hienGiaoDich(); } catch (Exception ex) { ex.printStackTrace(); } ChonThaoTacFrame.this.setVisible(false); } }); jBt_xn2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jCheck_tctk.isSelected()) { try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(7); dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + (String) jComboBox2.getSelectedItem()); dout.flush(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy Ra\n Thm Ch Tht Bi..."); } JOptionPane.showMessageDialog(rootPane, "Thm Ch Ti Khon Thnh Cng.."); } else { System.out.println("nothing to do..."); } } }); jBt_xtk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(11); String sent = (String) (jComboBox1.getSelectedItem()) + "\n" + noAcc.getCustomer(); dout.writeUTF(sent); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); byte check = din.readByte(); if (check == 1) { JOptionPane.showMessageDialog(rootPane, "xoa tai khoan thanh cong"); } else { JOptionPane.showMessageDialog(rootPane, "<html>xoa tai khoan <b>khong</b> thanh cong <br> chi chu chinh moi co the xoa tai khoan</html>"); } } catch (Exception ee) { ee.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "Li Kt Ni ,Vui Lng Kim Tra Li.."); } } }); /*dont touch*/ jBt_ql.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { noAcc.setVisible(true); ChonThaoTacFrame.this.setVisible(false); } }); /*dont touch*/ jComboBox1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); jComboBox2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); /*dont touch jcheckbox*/ jCheck_tctk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jCheck_tctk.isSelected()) { jLabel4.setVisible(true); jComboBox2.setVisible(true); jBt_xn2.setVisible(true); } else { jLabel4.setVisible(false); jComboBox2.setVisible(false); jBt_xn2.setVisible(false); } } }); jCheck_gt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jCheck_gt.isSelected()) { if (jCheck_rt.isSelected()) { jCheck_rt.setSelected(false); } jLabel2.setVisible(true); jLabel3.setVisible(true); jTextField1.setVisible(true); jBt_xn1.setVisible(true); } else { jLabel2.setVisible(false); jLabel3.setVisible(false); jTextField1.setVisible(false); jBt_xn1.setVisible(false); } } }); jCheck_rt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jCheck_rt.isSelected()) { if (jCheck_gt.isSelected()) { jCheck_gt.setSelected(false); } jLabel2.setVisible(true); jLabel3.setVisible(true); jTextField1.setVisible(true); jBt_xn1.setVisible(true); } else { jLabel2.setVisible(false); jLabel3.setVisible(false); jTextField1.setVisible(false); jBt_xn1.setVisible(false); } } }); /*dont touch jcheckbox*/ }
From source file:com.meh.CopyProxy.java
private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return;/*from ww w. jav a 2s . c om*/ } Log.d(tag, "processing"); String url = request.getRequestLine().getUri(); HttpResponse realResponse = download(url); if (realResponse == null) { return; } Log.d(tag, "downloading..."); InputStream data = realResponse.getEntity().getContent(); try { byte[] buffer = new byte[1024 * 50]; int readBytes; while (isRunning && (readBytes = data.read(buffer, 0, buffer.length)) != -1) { client.getOutputStream().write(buffer, 0, readBytes); } } catch (Exception e) { Log.e("", e.getMessage(), e); } finally { if (data != null) { data.close(); } client.close(); } }
From source file:com.android.development.Connectivity.java
private void onDefaultSocket() { InetAddress remote = null;// w ww .ja v a 2s. c om try { remote = InetAddress.getByName("www.flickr.com"); } catch (Exception e) { Log.e(TAG, "exception getting remote InetAddress: " + e); return; } Log.e(TAG, "remote addr =" + remote); Socket socket = null; try { socket = new Socket(remote, 80); } catch (Exception e) { Log.e(TAG, "Exception creating socket: " + e); return; } try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("Hi flickr"); Log.e(TAG, "written"); } catch (Exception e) { Log.e(TAG, "Exception writing to socket: " + e); return; } }
From source file:com.envirover.spl.SPLGroungControlTest.java
@Test public void testMTMessagePipeline() { System.out.println("MT TEST: Testing MT message pipeline..."); Socket client = null; DataOutputStream out = null;//ww w.j av a2 s. c o m try { System.out.printf("MT TEST: Connecting to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort()); System.out.println(); client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort()); System.out.printf("MT TEST: Connected to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort()); System.out.println(); out = new DataOutputStream(client.getOutputStream()); MAVLinkPacket packet = getSamplePacket(); out.write(packet.encodePacket()); out.flush(); System.out.printf("MT TEST: MAVLink message sent: msgid = %d", packet.msgid); System.out.println(); Thread.sleep(5000); System.out.println("MT TEST: Complete."); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (out != null) out.close(); if (client != null) client.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.raddle.tools.ClipboardTransferMain.java
private void shutdown() { Socket socket = null; try {//from w w w . j ava2 s . c o m tostop = true; socket = new Socket("127.0.0.1", Integer.parseInt(portTxt.getText())); socket.setSoTimeout(2000); ClipCommand cmd = new ClipCommand(); cmd.setCmdCode(ClipCommand.CMD_SHUTDOWN); // ?? ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); out.writeObject(cmd); } catch (Exception e) { updateMessage("??:" + e.getMessage()); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } }