public String getRedirect(String host, boolean isRobots) { String result = null; try { Socket socket = new Socket(getDomain(host), 80); PrintWriter writer = new PrintWriter(socket.getOutputStream()); if (!isRobots) { writer.print("GET " + getPath(host) + " HTTP/1.1\r\n"); writer.print("Host: " + getDomain(host) + "\r\n"); writer.print("\r\n"); writer.flush(); } else { writer.print("GET /robots.txt HTTP/1.1\r\n"); writer.print("Host: " + host + "\r\n"); writer.print("\r\n"); writer.flush(); } BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = ""; String target = "Location: http://"; int targetCount = 0; boolean startNotingRedirectHost = false; String redirectHost = ""; while ((line = reader.readLine()) != null) { for (int i = 0; i < line.length(); i++) { if (targetCount == target.length()) { targetCount = 0; startNotingRedirectHost = true; } if (startNotingRedirectHost) { if (line.charAt(i) != '\n') redirectHost = redirectHost + line.charAt(i); } if (line.charAt(i) == target.charAt(targetCount)) { targetCount++; } else { targetCount = 0; } } if (startNotingRedirectHost) { startNotingRedirectHost = false; return redirectHost; } } reader.close(); socket.close(); } catch (IOException e) { return null; } return result; }
public void run() { try { try { scanner = new Scanner(socket.getInputStream()); out = new PrintWriter(socket.getOutputStream()); while (true) { checkConn(); if (!scanner.hasNext()) { return; } msg = scanner.nextLine(); System.out.println("Client said: " + msg); for (int i = 1; i <= Server.ConnectionArray.size(); i++) { Socket tSocket = (Socket) Server.ConnectionArray.get(i - 1); PrintWriter tOut = new PrintWriter(tSocket.getOutputStream()); tOut.println(msg); tOut.flush(); System.out.println("Sent to: " + tSocket.getLocalAddress().getHostName()); } } } finally { socket.close(); } } catch (IOException e) { e.printStackTrace(); } }
public Integer handleResponse(ESXX esxx, Context cx, Response response) throws Exception { // Output HTTP headers final PrintWriter out = new PrintWriter(createWriter(outStream, "US-ASCII")); out.println("Status: " + response.getStatus()); out.println("Content-Type: " + response.getContentType(true)); response.enumerateHeaders( new Response.HeaderEnumerator() { public void header(String name, String value) { out.println(name + ": " + value); } }); out.println(); out.flush(); response.writeResult(esxx, cx, outStream); getErrorWriter().flush(); getDebugWriter().flush(); outStream.flush(); return 0; }
/** Starts receiving and broadcasting messages. */ public void run() { PrintWriter out = null; try { out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream())); // inform the server of this new client ChatServer.this.addClient(out); out.print("Welcome to JavaChat! "); out.println("Enter BYE to exit."); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream())); for (; ; ) { String msg = in.readLine(); if (msg == null) { break; } else { if (msg.trim().equals("BYE")) break; System.out.println("Received: " + msg); // broadcast the receive message ChatServer.this.broadcast(msg); } } incoming.close(); ChatServer.this.removeClient(out); } catch (Exception e) { if (out != null) { ChatServer.this.removeClient(out); } e.printStackTrace(); } }
/** * 向服务器发送命令行,给服务器端处理 * * @param lines 命令行 */ public static void clientSend(String[] lines) { if (lines != null && lines.length <= 0) { return; } Socket socket = null; PrintWriter writer = null; try { socket = new Socket("localhost", port); writer = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream(), EncodeConstants.ENCODING_UTF_8))); for (int i = 0; i < lines.length; i++) { writer.println(lines[i]); } writer.flush(); } catch (Exception e) { FRContext.getLogger().error(e.getMessage(), e); } finally { try { writer.close(); socket.close(); } catch (IOException e) { FRContext.getLogger().error(e.getMessage(), e); } } }
/** * create a Bufferedreader that read from the open url The parameter of the search term research * can be setup using the various command */ private boolean download() { buffer = new StringBuilder(); // --1. Encode url? // --2. Do the work try { url = new URL(composite_url); // Config.log("ESearch for: "+search_term); } catch (MalformedURLException e) { Config.log("Error: URL is not good.\n" + composite_url); } try { if (in_connection_open) in_connection.close(); in_connection = new BufferedReader(new InputStreamReader(url.openStream())); if (in_connection != null) in_connection_open = true; String inputLine = ""; if (isOutputToDisk()) output = new PrintWriter(new FileWriter(new File(filename))); while ((inputLine = in_connection.readLine()) != null) { if (!this.isOutputToDisk()) { buffer.append(inputLine + "\n"); } else { output.println(inputLine); } } if (isOutputToDisk()) { output.flush(); output.close(); } } catch (IOException e) { Config.log("Unable to download from..." + composite_url); return false; } return true; }
private String handleConnection() { String content = null; try { PrintWriter streamWriter = new PrintWriter(connection.getOutputStream()); BufferedReader streamReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); content = streamReader.readLine(); // System.out.println(content); log.debug("receiveing begin............\r\n"); log.debug(content); log.debug("receiveing end........"); streamWriter.println(content + "\r\n"); // streamWriter.println("hello\r\n"); streamWriter.flush(); streamReader.close(); streamWriter.close(); // connection.close(); return content; } catch (FileNotFoundException e) { // System.out.println("Could not find requested file on the server."); log.error("Could not find requested file on the server."); return content; } catch (IOException e) { // System.out.println("Error handling a client: " + e); log.error("Error handling a client: " + e); return content; } }
public static void main(String[] args) { if (args.length < 1) { System.out.println("Need port"); return; } int port = Integer.parseInt(args[0]); try { ServerSocket server = new ServerSocket(port); System.out.println( "Login on " + server.getInetAddress().toString() + ":" + server.getLocalPort() + ".\nExit with a single x"); Socket client = server.accept(); LineNumberReader in = new LineNumberReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); while (true) { String str = in.readLine(); System.out.println(str); if (str.equals("x") == true) { client.close(); server.close(); break; } out.println(str); out.flush(); } } catch (IOException ex) { } }
public static void main(String[] args) { try { ServerSocket server = null; try { server = new ServerSocket(4700); } catch (Exception e) { System.out.println("Can Not Listem To:" + e); } Socket socket = null; try { socket = server.accept(); } catch (Exception e) { System.out.println("Error: " + e); } String line; BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter os = new PrintWriter(socket.getOutputStream()); BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Client:" + is.readLine()); line = sin.readLine(); while (!line.equals("bye")) { os.println(line); os.flush(); System.out.println("Server:" + line); System.out.println("Client:" + is.readLine()); line = sin.readLine(); } os.close(); is.close(); socket.close(); server.close(); } catch (Exception e) { System.out.println("Error:" + e); } }
private boolean write(String message) { if (socket != null) { p.println(message); p.flush(); } return true; }
public boolean doUsername() { try { if (username.equals("")) { String x = JOptionPane.showInputDialog(null, "Please enter a username."); if (x == null) { return false; } if (x.equals("")) { return false; } username = x; } toServer.println("USERNAME_RQUEST"); toServer.println(username); toServer.flush(); // System.out.println("sent username"); // keep doing until has a username that is unused String reply = inFromServer.readLine(); // System.out.println("this is the reply:" + reply); while (reply.equals("USERNAME_USED")) { String temp = JOptionPane.showInputDialog( null, "Please enter a new username, \"" + username + "\" has been taken on this server or is invalid."); if (temp == null) { return false; } username = temp; toServer.println(username); toServer.flush(); reply = inFromServer.readLine(); // System.out.println("This is reply" + reply); } JOptionPane.showMessageDialog( null, "Username \"" + username + "\" has been accepted by the server."); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } }
private void sendMessage(String msg) throws IOException { // System.out.println("[AdminClient] Send Message: '" + msg + "'"); // append special chars to idicate the end of the message msg += "$$"; PrintWriter writer = new PrintWriter(m_remoteSocket.getOutputStream()); writer.print(msg); writer.flush(); }
/** @param args the command line arguments */ public static void main(String[] args) throws IOException { // TODO code application logic here Socket socket = null; BufferedReader read = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket("10.151.34.155", 6666); read = new BufferedReader(new InputStreamReader(System.in)); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); } catch (IOException ex) { Logger.getLogger(UTSProgjar.class.getName()).log(Level.SEVERE, null, ex); } String textToServer; while ((textToServer = read.readLine()) != null) { out.print(textToServer + "\r\n"); out.flush(); String messageFromServer; while ((messageFromServer = textToServer = in.readLine()) != null) { System.out.println(messageFromServer); } } Integer intToServer; while ((intToServer = Integer.parseInt(read.readLine())) != null) { out.print(intToServer + "\r\n"); out.flush(); String messageFromServer; while ((messageFromServer = textToServer = in.readLine()) != null) { System.out.println(messageFromServer); } } out.close(); in.close(); read.close(); socket.close(); }
public void send(String s) throws IOException { if (s != null) { out.println(s); out.flush(); } if ((line = in.readLine()) != null) // output the response System.out.println(line); }
// メッセージをサーバーに送信する public void sendMessage(String msg) { try { OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output); writer.println(msg); writer.flush(); } catch (Exception err) { msgTextArea.append("ERROR>" + err + "\n"); } }
private static NameValuePair<Long> poll(Config.HostInfo host, long minAge) throws IOException { NameValuePair<Long> run = null; URL target = new URL(host.url, SERVLET_PATH); HttpURLConnection c; if (host.proxyHost != null) c = (HttpURLConnection) target.openConnection( new Proxy( Proxy.Type.HTTP, new InetSocketAddress(host.proxyHost, host.proxyPort))); else c = (HttpURLConnection) target.openConnection(); try { c.setRequestMethod("POST"); c.setConnectTimeout(2000); c.setDoOutput(true); c.setDoInput(true); PrintWriter out = new PrintWriter(c.getOutputStream()); out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&minage=" + minAge); out.flush(); out.close(); } catch (SocketTimeoutException e) { logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e); throw new IOException("Socket connect timeout"); } int responseCode = c.getResponseCode(); if (responseCode == HttpServletResponse.SC_OK) { InputStream is = c.getInputStream(); // The input is a one liner in the form runId\tAge byte[] buffer = new byte[256]; // Very little cost for this new/GC. int size = is.read(buffer); // We have to close the input stream in order to return it to // the cache, so we get it for all content, even if we don't // use it. It's (I believe) a bug that the content handlers used // by getContent() don't close the input stream, but the JDK team // has marked those bugs as "will not fix." is.close(); StringTokenizer t = new StringTokenizer(new String(buffer, 0, size), "\t\n"); run = new NameValuePair<Long>(); run.name = t.nextToken(); run.value = Long.parseLong(t.nextToken()); } else if (responseCode != HttpServletResponse.SC_NO_CONTENT) { logger.warning("Polling " + target + " got response code " + responseCode); } return run; }
String getChatHistory(String user, String pass) { int cmdID = commID++; connect(user, pass); try { out.println(cmdID + ";chath"); out.flush(); return (String) receiveReply(cmdID); } catch (Exception r) { r.printStackTrace(); } return null; }
String cancelShares(String user, String pass, int id, int sellid) { int cmdID = commID++; connect(user, pass); try { out.println(cmdID + ";cancel:" + id + ":" + sellid); out.flush(); return (String) receiveReply(cmdID); } catch (Exception r) { r.printStackTrace(); } return null; }
String sendChat(String s, String user, String pass) { int cmdID = commID++; connect(user, pass); try { out.println(cmdID + ";chat:" + s.trim()); out.flush(); return (String) receiveReply(cmdID); } catch (Exception r) { r.printStackTrace(); } return null; }
java.util.List<Double> getHistory(String comp, int count) { int cmdID = commID++; // connect(user.getName(),user.getPassword()); try { out.println(cmdID + ";" + "getch:" + comp + ":" + Integer.toString(count)); out.flush(); return (java.util.List<Double>) receiveReply(cmdID); } catch (Exception r) { r.printStackTrace(); } return null; }
public static void main(String[] pArgs) { if (pArgs.length < 3) { System.out.println("usage: java Client host port boardnum"); return; } try { Socket lSocket = new Socket(pArgs[0], Integer.parseInt(pArgs[1])); PrintWriter lOut = new PrintWriter(lSocket.getOutputStream()); BufferedReader lIn = new BufferedReader(new InputStreamReader(lSocket.getInputStream())); lOut.println(pArgs[2]); lOut.flush(); String lLine = lIn.readLine(); // read number of rows int lNumRows = Integer.parseInt(lLine); // now, we should find a path from the player to any goal // we've found our solution String lMySol = SokobanSolver.findSolution(Matrix.tileMatrixFromBufferedReader(lIn, lNumRows)); // these formats are also valid: // String lMySol="URRUULDLLULLDRRRRLDDRURUDLLUR"; // String lMySol="0 3 3 0 0 2 1 2 2 0 2 2 1 3 3 3 3 2 1 1 3 0 3 0 1 2 2 0 3"; // send the solution to the server lOut.println(lMySol); lOut.flush(); // read answer from the server lLine = lIn.readLine(); System.out.println(lLine); } catch (Throwable t) { t.printStackTrace(); } }
void placeOrder(final User user, String cmd, Company comp, int qty, int id) { int cmdID = commID++; connect(user.getName(), user.getPassword()); try { out.println(cmdID + ";" + cmd + ":" + comp.name + ":" + Integer.toString(qty) + ":" + id); out.flush(); Shares pen = (Shares) receiveReply(cmdID); user.getPendingShares().add(pen); user.dataChanged(); } catch (Exception r) { r.printStackTrace(); } }
public void sendToAll(String msg) { Iterator it = clientOutputStream.iterator(); while (it.hasNext()) { try { PrintWriter writer = (PrintWriter) it.next(); writer.println(msg); writer.flush(); } catch (Exception ex) { } } } // end send ToAll
protected void sendRequest(PrintWriter out, String[] msg) { for (int i = 0; i < msg.length; i++) { if (Debug.get(Debug.Communication)) { System.err.println(">>>" + msg[i]); } out.print(msg[i] + crlf); } if (Debug.get(Debug.Communication)) { System.err.println(">>>"); } out.print(crlf); out.flush(); }
public void disconnect() { int cmdID = commID++; this.connected = false; try { out.println(cmdID + ";logout"); out.flush(); in.close(); out.close(); socket.close(); } catch (IOException ex) { System.err.println("Server stop failed."); } }
String login(String domain, String user, String pass) { int cmdID = commID++; this.domain = domain; connect(user, pass); try { out.println(cmdID + ";login:"******":" + pass); out.flush(); String rep = (String) receiveReply(cmdID); return rep.split(":")[0]; } catch (Exception r) { r.printStackTrace(); } return null; }
public String getFile(String fileNameToGet) { StringBuffer fileLines = new StringBuffer(); try { socketWriter.println(fileNameToGet); socketWriter.flush(); String line = null; while ((line = socketReader.readLine()) != null) fileLines.append(line + "\n"); } catch (IOException e) { System.out.println("Error reading from file: " + fileNameToGet); } return fileLines.toString(); }
User getUserDetails(String user, String pass) { int cmdID = commID++; connect(user, pass); try { usrD = 1; out.println(cmdID + ";gud"); out.flush(); User vv = (User) receiveReply(cmdID); usrD = 0; return vv; } catch (Exception r) { r.printStackTrace(); } return null; }
public static void savePluginsList(Collection<String> ids, boolean append, File plugins) throws IOException { if (!plugins.isFile()) { FileUtil.ensureCanCreateFile(plugins); } PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(plugins, append))); try { for (String id : ids) { printWriter.println(id); } printWriter.flush(); } finally { printWriter.close(); } }
public void run() { try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream()); while (!authentifier) { out.println("Entrez votre login :"******"Entrez votre mot de passe :"); out.flush(); pass = in.readLine(); if (isValid(login, pass)) { out.println("connecte"); System.out.println(login + " vient de se connecter "); out.flush(); authentifier = true; } else { out.println("erreur"); out.flush(); } } t2 = new Thread(new Chat_ClientServeur(socket, login)); t2.start(); } catch (IOException e) { System.err.println(login + " ne répond pas !"); } }