List of usage examples for java.net Socket getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:net.arccotangent.pacchat.net.ConnectionHandler.java
public void run() { try {//from w w w . j av a 2 s.c om String line1 = input.readLine(); switch (line1) { case "101 ping": ch_log.i("Client pinged us, responding with an acknowledgement."); output.write("102 pong"); output.newLine(); output.flush(); output.close(); break; case "302 request key update": ch_log.i("Client is requesting a key update."); KeyUpdate update = new KeyUpdate(ip); KeyUpdateManager.addPendingUpdate(connection_id, update); while (KeyUpdateManager.getUpdate(connection_id).isProcessed()) { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } boolean accepted = KeyUpdateManager.getUpdate(connection_id).isAccepted(); KeyUpdateManager.completeIncomingUpdate(connection_id, KeyUpdateManager.getUpdate(connection_id)); if (accepted) { ch_log.i("Accepting key update"); try { output.write("303 update"); output.newLine(); output.flush(); String pubkeyB64 = input.readLine(); byte[] pubEncoded = Base64.decodeBase64(pubkeyB64); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); output.close(); input.close(); KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { ch_log.e("Error updating sender's key!"); e.printStackTrace(); } } else { ch_log.i("Rejecting key update."); output.write("304 no update"); output.newLine(); output.flush(); output.close(); } break; case "301 getkey": ch_log.i("Client requested our public key, sending."); String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded()); output.write(pubkeyB64); output.newLine(); output.flush(); output.close(); break; case "200 encrypted message": //incoming encrypted message ch_log.i("Client sent an encrypted message, attempting verification and decryption."); PrivateKey privkey = Main.getKeypair().getPrivate(); String cryptedMsg = input.readLine() + "\n" + input.readLine() + "\n" + input.readLine(); ch_log.i("Checking for sender's public key."); if (KeyManager.checkIfIPKeyExists(ip)) { ch_log.i("Public key found."); } else { ch_log.i("Public key not found, requesting key from their server."); try { Socket socketGetkey = new Socket(); socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip), Server.PORT), 1000); BufferedReader inputGetkey = new BufferedReader( new InputStreamReader(socketGetkey.getInputStream())); BufferedWriter outputGetkey = new BufferedWriter( new OutputStreamWriter(socketGetkey.getOutputStream())); outputGetkey.write("301 getkey"); outputGetkey.newLine(); outputGetkey.flush(); String sender_pubkeyB64 = inputGetkey.readLine(); byte[] pubEncoded = Base64.decodeBase64(sender_pubkeyB64); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); outputGetkey.close(); inputGetkey.close(); KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec)); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { ch_log.e("Error saving sender's key!"); e.printStackTrace(); } } PacchatMessage message = MsgCrypto.decryptAndVerifyMessage(cryptedMsg, privkey, KeyManager.loadKeyByIP(ip)); String msg = message.getMessage(); boolean verified = message.isVerified(); boolean decrypted = message.isDecryptedSuccessfully(); String ANSI_RESET = "\u001B[0m"; String ANSI_CYAN = "\u001B[36m"; String ANSI_BOLD = "\u001B[1m"; if (verified && decrypted) { ch_log.i("Acknowledging message."); output.write("201 message acknowledgement"); output.newLine(); output.flush(); output.close(); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET); } else if (!verified && decrypted) { ch_log.w("Notifying client that message authenticity was not verified."); output.write("203 unable to verify"); output.newLine(); output.flush(); output.close(); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET); } else if (!verified) { ch_log.w("Notifying client that message could not be decrypted."); output.write("202 unable to decrypt"); output.newLine(); output.flush(); output.close(); } break; case "201 message acknowledgement": ch_log.i("Client sent an invalid message acknowledgement."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); case "202 unable to decrypt": ch_log.i("Client sent an invalid 'unable to decrypt' transmission."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); case "203 unable to verify": ch_log.i("Client sent an invalid 'unable to verify' transmission."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); default: ch_log.i("Client sent an invalid request header: " + line1); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); break; } } catch (IOException e) { ch_log.e("Error in connection handler " + connection_id); e.printStackTrace(); } }
From source file:net.lightbody.bmp.proxy.jetty.util.ThreadedServer.java
/** * Handle new connection. If access is required to the actual socket, override this method * instead of handleConnection(InputStream in,OutputStream out). The default implementation of * this just calls handleConnection(InputStream in,OutputStream out). *//*from ww w .ja v a2s . c o m*/ protected void handleConnection(Socket connection) throws IOException { if (log.isDebugEnabled()) log.debug("Handle " + connection); InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream(); handleConnection(in, out); out.flush(); in = null; out = null; connection.close(); }
From source file:edu.cmu.ark.AnalysisUtilities.java
public ParseResult parseSentence(String sentence) { String result = ""; //System.err.println(sentence); //see if a parser socket server is available int port = new Integer(GlobalProperties.getProperties().getProperty("parserServerPort", "5556")); String host = "127.0.0.1"; Socket client; PrintWriter pw;/* w w w.j a v a 2s. c om*/ BufferedReader br; String line; Tree parse = null; double parseScore = Double.MIN_VALUE; try { client = new Socket(host, port); pw = new PrintWriter(client.getOutputStream()); br = new BufferedReader(new InputStreamReader(client.getInputStream())); pw.println(sentence); pw.flush(); //flush to complete the transmission while ((line = br.readLine()) != null) { //if(!line.matches(".*\\S.*")){ // System.out.println(); //} if (br.ready()) { line = line.replaceAll("\n", ""); line = line.replaceAll("\\s+", " "); result += line + " "; } else { parseScore = new Double(line); } } br.close(); pw.close(); client.close(); if (parse == null) { parse = readTreeFromString("(ROOT (. .))"); parseScore = -99999.0; } if (GlobalProperties.getDebug()) System.err.println("result (parse):" + result); parse = readTreeFromString(result); return new ParseResult(true, parse, parseScore); } catch (Exception ex) { if (GlobalProperties.getDebug()) System.err.println("Could not connect to parser server."); //ex.printStackTrace(); } System.err.println("parsing:" + sentence); //if socket server not available, then use a local parser object if (parser == null) { try { Options op = new Options(); String serializedInputFileOrUrl = GlobalProperties.getProperties().getProperty("parserGrammarFile", "config" + File.separator + "englishFactored.ser.gz"); parser = new LexicalizedParser(serializedInputFileOrUrl, op); int maxLength = new Integer(GlobalProperties.getProperties().getProperty("parserMaxLength", "40")) .intValue(); parser.setMaxLength(maxLength); parser.setOptionFlags("-outputFormat", "oneline"); } catch (Exception e) { e.printStackTrace(); } } try { if (parser.parse(sentence)) { parse = parser.getBestParse(); //remove all the parent annotations (this is a hacky way to do it) String ps = parse.toString().replaceAll("\\[[^\\]]+/[^\\]]+\\]", ""); parse = AnalysisUtilities.getInstance().readTreeFromString(ps); parseScore = parser.getPCFGScore(); return new ParseResult(true, parse, parseScore); } } catch (Exception e) { } parse = readTreeFromString("(ROOT (. .))"); parseScore = -99999.0; return new ParseResult(false, parse, parseScore); }
From source file:Server.java
/** * This is the method that Listener objects call when they accept a * connection from a client. It either creates a Connection object for the * connection and adds it to the list of current connections, or, if the * limit on connections has been reached, it closes the connection. *///from www .j a v a 2s. com protected synchronized void addConnection(Socket s, Service service) { // If the connection limit has been reached if (connections.size() >= maxConnections) { try { // Then tell the client it is being rejected. PrintWriter out = new PrintWriter(s.getOutputStream()); out.print("Connection refused; " + "the server is busy; please try again later.\n"); out.flush(); // And close the connection to the rejected client. s.close(); // And log it, of course log("Connection refused to " + s.getInetAddress().getHostAddress() + ":" + s.getPort() + ": max connections reached."); } catch (IOException e) { log(e); } } else { // Otherwise, if the limit has not been reached // Create a Connection thread to handle this connection Connection c = new Connection(s, service); // Add it to the list of current connections connections.add(c); // Log this new connection log("Connected to " + s.getInetAddress().getHostAddress() + ":" + s.getPort() + " on port " + s.getLocalPort() + " for service " + service.getClass().getName()); // And start the Connection thread to provide the service c.start(); } }
From source file:MedArkRef.AnalysisUtilities.java
public arkref.parsestuff.AnalysisUtilities.ParseResult parseSentence(String sentence) { String result = ""; //System.err.println(sentence); //see if a parser socket server is available int port = new Integer(GlobalProperties.getProperties().getProperty("parserServerPort", "5556")); String host = "127.0.0.1"; Socket client; PrintWriter pw;//w ww .ja v a 2 s .co m BufferedReader br; String line; Tree parse = null; double parseScore = Double.MIN_VALUE; try { client = new Socket(host, port); pw = new PrintWriter(client.getOutputStream()); br = new BufferedReader(new InputStreamReader(client.getInputStream())); pw.println(sentence); pw.flush(); //flush to complete the transmission while ((line = br.readLine()) != null) { //if(!line.matches(".*\\S.*")){ // System.out.println(); //} if (br.ready()) { line = line.replaceAll("\n", ""); line = line.replaceAll("\\s+", " "); result += line + " "; } else { parseScore = new Double(line); } } br.close(); pw.close(); client.close(); if (parse == null) { parse = readTreeFromString("(ROOT (. .))"); parseScore = -99999.0; } if (GlobalProperties.getDebug()) System.err.println("result (parse):" + result); parse = readTreeFromString(result); return new arkref.parsestuff.AnalysisUtilities.ParseResult(true, parse, parseScore); } catch (Exception ex) { if (GlobalProperties.getDebug()) System.err.println("Could not connect to parser server."); //ex.printStackTrace(); } System.err.println("parsing:" + sentence); //if socket server not available, then use a local parser object if (parser == null) { try { Options op = new Options(); String serializedInputFileOrUrl = GlobalProperties.getProperties().getProperty("parserGrammarFile", "config" + File.separator + "englishFactored.ser.gz"); parser = new LexicalizedParser(serializedInputFileOrUrl, op); int maxLength = new Integer(GlobalProperties.getProperties().getProperty("parserMaxLength", "40")) .intValue(); parser.setMaxLength(maxLength); parser.setOptionFlags("-outputFormat", "oneline"); } catch (Exception e) { e.printStackTrace(); } } try { if (parser.parse(sentence)) { parse = parser.getBestParse(); //remove all the parent annotations (this is a hacky way to do it) String ps = parse.toString().replaceAll("\\[[^\\]]+/[^\\]]+\\]", ""); parse = AnalysisUtilities.getInstance().readTreeFromString(ps); parseScore = parser.getPCFGScore(); return new arkref.parsestuff.AnalysisUtilities.ParseResult(true, parse, parseScore); } } catch (Exception e) { } parse = readTreeFromString("(ROOT (. .))"); parseScore = -99999.0; return new arkref.parsestuff.AnalysisUtilities.ParseResult(false, parse, parseScore); }
From source file:com.cyberway.issue.crawler.fetcher.FetchFTP.java
/** * Saves the given socket to the given recorder. * /*from www.jav a 2s . c o m*/ * @param curi the curi that owns the recorder * @param socket the socket whose streams to save * @param recorder the recorder to save them to * @throws IOException if a network or file error occurs * @throws InterruptedException if the thread is interrupted */ private void saveToRecorder(CrawlURI curi, Socket socket, HttpRecorder recorder) throws IOException, InterruptedException { curi.setHttpRecorder(recorder); recorder.markContentBegin(); recorder.inputWrap(socket.getInputStream()); recorder.outputWrap(socket.getOutputStream()); // Read the remote file/dir listing in its entirety. long softMax = 0; long hardMax = getMaxLength(curi); long timeout = (long) getTimeout(curi) * 1000; int maxRate = getFetchBandwidth(curi); RecordingInputStream input = recorder.getRecordedInput(); input.setLimits(hardMax, timeout, maxRate); input.readFullyOrUntil(softMax); }
From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java
protected void write(Socket socket, MessageObject messageObject) throws Exception { byte[] data = messageObject.getEncodedData().getBytes(connector.getCharsetEncoding()); LlpProtocol protocol = connector.getLlpProtocol(); BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), connector.getBufferSize()); protocol.write(bos, data);/* w ww .j av a2s .co m*/ bos.flush(); }
From source file:TalkServerThread.java
TalkServerThread(Socket socket, TalkServer server) throws IOException { super("TalkServer"); is = new BufferedReader( new InputStreamReader(socket.getInputStream())); os = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); if (is == null) { System.err.println("TalkServerThread: Input stream seemed " + "to be created successfully, but it's null."); throw new IOException(); }//from w w w . j a va 2 s . co m if (os == null) { System.err.println("TalkServerThread: Output stream seemed " + "to be created successfully, but it's null."); throw new IOException(); } this.socket = socket; this.server = server; }
From source file:com.trigger_context.Main_Service.java
private void takeAction(String mac, InetAddress ip) { noti("comes to ", mac); SharedPreferences conditions = getSharedPreferences(mac, MODE_PRIVATE); Map<String, ?> cond_map = conditions.getAll(); Set<String> key_set = cond_map.keySet(); Main_Service.main_Service.noti(cond_map.toString(), ""); if (key_set.contains("SmsAction")) { String number = conditions.getString("SmsActionNumber", null); String message = conditions.getString("SmsActionMessage", null); try {//from w w w . j a v a 2 s .co m SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(number, null, message, null, null); noti("Sms Sent To : ", "" + number); } catch (Exception e) { noti("Sms Sending To ", number + "Failed"); } } if (key_set.contains("OpenWebsiteAction")) { Intent dialogIntent = new Intent(getBaseContext(), Action_Open_Url.class); dialogIntent.putExtra("urlAction", (String) cond_map.get("urlAction")); dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplication().startActivity(dialogIntent); } if (key_set.contains("ToggleAction")) { if (key_set.contains("bluetoothAction") && conditions.getBoolean("bluetoothAction", false)) { final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothAdapter.enable(); } else if (key_set.contains("bluetoothAction")) { final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothAdapter.disable(); } if (key_set.contains("wifiAction") && conditions.getBoolean("wifiAction", false)) { final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); wm.setWifiEnabled(true); } else if (key_set.contains("wifiAction")) { final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); wm.setWifiEnabled(false); } } if (key_set.contains("TweetAction")) { Intent dialogIntent = new Intent(getBaseContext(), Action_Post_Tweet.class); dialogIntent.putExtra("tweetTextAction", (String) cond_map.get("tweetTextAction")); dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplication().startActivity(dialogIntent); } if (key_set.contains("EmailAction")) { Intent dialogIntent = new Intent(getBaseContext(), Action_Email_Client.class); dialogIntent.putExtra("toAction", (String) cond_map.get("toAction")); dialogIntent.putExtra("subjectAction", (String) cond_map.get("subjectAction")); dialogIntent.putExtra("emailMessageAction", (String) cond_map.get("emailMessageAction")); dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplication().startActivity(dialogIntent); } if (key_set.contains("RemoteServerCmd")) { String text = conditions.getString("cmd", null); new Thread(new SendData("224.0.0.1", 9876, text)).start(); } // network activities from here. // in all network actions send username first if (key_set.contains("FileTransferAction")) { String path = conditions.getString("filePath", null); SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE); String usrName = my_data.getString("name", "userName"); // type 1 try { Socket socket = new Socket(ip, COMM_PORT); DataOutputStream out = null; out = new DataOutputStream(socket.getOutputStream()); out.writeUTF(usrName); out.writeInt(1); sendFile(out, path); noti("Sent " + path + " file to :", getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (key_set.contains("ccfMsgAction")) { String msg = conditions.getString("ccfMsg", null); SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE); String usrName = my_data.getString("name", "userName"); // type 2 is msg try { Socket socket = new Socket(ip, COMM_PORT); DataOutputStream out = null; out = new DataOutputStream(socket.getOutputStream()); out.writeUTF(usrName); out.writeInt(2); out.writeUTF(msg); noti("Sent msg : '" + msg + "'", "to : " + getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (key_set.contains("sync")) { SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE); String usrName = my_data.getString("name", "userName"); // type 3 is sync try { Socket socket = new Socket(ip, COMM_PORT); DataInputStream in = new DataInputStream(socket.getInputStream()); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeUTF(usrName); out.writeInt(3); senderSync(in, out, Environment.getExternalStorageDirectory().getPath() + "/TriggerSync/"); noti("Synced with:", getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:edu.vt.middleware.gator.server.SocketServerTest.java
/** * Tests connecting to the socket server and sending a logging event that * should be written to configured appenders. * * @throws Exception On errors.// w ww . ja v a 2 s . c o m */ @Test public void testConnectAndLog() throws Exception { final Socket sock = new Socket(); try { final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()), server.getPort()); sock.connect(addr, SOCKET_CONNECT_TIMEOUT); // Allow the socket server time to build the hierarchy // before sending a test logging event Thread.sleep(2000); Assert.assertEquals(1, server.getLoggingEventHandlers().size()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending test logging event."); } final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream()); oos.writeObject(new MockEvent(TEST_MESSAGE)); oos.flush(); } finally { if (sock.isConnected()) { sock.close(); } } // Pause to allow time for logging events to be written Thread.sleep(2000); // Client socket close should trigger cleanup of server handler mapping Assert.assertEquals(0, server.getLoggingEventHandlers().size()); // Ensure test message was written to file Assert.assertTrue(readTextFile(LOG_FILE).contains(TEST_MESSAGE)); }