public void run() { if (ServerSocket == null) return; while (true) { try { InetAddress address; int port; DatagramPacket packet; byte[] data = new byte[1460]; packet = new DatagramPacket(data, data.length); ServerSocket.receive(packet); // // address = packet.getAddress(); port = packet.getPort(); System.out.println("get the Client port is: " + port); System.out.println("get the data length is: " + data.length); FileWriter fw = new FileWriter("Fortunes.txt"); PrintWriter out = new PrintWriter(fw); for (int i = 0; i < data.length; i++) { out.print(data[i] + " "); } out.close(); System.out.println("Data has been writen to destination!"); packet = new DatagramPacket(data, data.length, address, port); ServerSocket.send(packet); System.out.println("Respond has been made!"); } catch (Exception e) { System.err.println("Exception: " + e); e.printStackTrace(); } } }
public static synchronized void publicRelay(String input) { PrintWriter out = null; for (OutputStream o : socketList) { out = new PrintWriter(o, true); out.println(" ** " + input); } }
/** * 向服务器发送命令行,给服务器端处理 * * @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); } } }
private boolean handleMsg(String str) { if (userId <= 0 || !KotoServer.loggedin.containsKey(userId)) { out.println("ERROR:NotLoggedIn"); return false; } String[] data = str.split(":", 2); if (!(data[0].length() > 0)) { out.println("ERROR:BadUser"); System.out.println("Unable to send message, target user does not exist"); return true; } int targetId; try { targetId = Integer.parseInt(data[0]); } catch (NumberFormatException e) { out.println("ERROR:BadUser"); System.out.println("Unable to send message, target user does not exist"); return true; } if (KotoServer.loggedin.containsKey(targetId)) { KotoServer.sendMsg(targetId, "MSG:" + userId + ":" + data[1]); System.out.println("sent message from user " + userId + " to " + targetId); } else if (KotoServer.users.containsKey(targetId)) { KotoServer.users.get(targetId).addMessage(str); System.out.println( "saved message from user" + userId + " to " + targetId + " for further deliver"); } else { out.println("ERROR:BadUser"); System.out.println("Unable to send message, target user does not exist"); } return true; }
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 void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Tracking Example"; HttpSession session = request.getSession(true); String heading; Integer accessCount = (Integer) session.getAttribute("accessCount"); if (accessCount == null) { accessCount = new Integer(0); heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } session.setAttribute("accessCount", accessCount); out.println( "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Info Type<TH>Value\n" + "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getId() + "\n" + "<TR>\n" + " <TD>Creation Time\n" + " <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" + " <TD>Time of Last Access\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" + " <TD>Number of Previous Accesses\n" + " <TD>" + accessCount + "\n" + "</TR>" + "</TABLE>\n"); // the following two statements show how to retrieve parameters in // the request. The URL format is something like: // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li String myname = request.getParameter("myname"); if (myname != null) out.println("Hey " + myname + "<br><br>"); out.println("</BODY></HTML>"); }
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; } }
/** * 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; }
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; }
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); } }
/** * Used to write Resources for a Subject. Literals will by-pass this method and use "Literal" * method. * * @param predicate PredicateNode * @param object ObjectNode * @param writer PrintWriter * @throws GraphException */ protected void writeStatement( Graph graph, SubjectNode subject, PredicateNode predicate, ObjectNode object, PrintWriter writer) throws GraphException { // Literals are written differently if (object instanceof Literal) { this.writeStatement(graph, subject, predicate, (Literal) object, writer); } else if (object instanceof BlankNode) { // write as: <predicateURI> *blank node as subject* </predicateURI> writer.println(" <" + this.getURI(predicate) + ">"); // write blank node as a "subject" this.writeSubject(graph, (BlankNode) object, writer); writer.println(" </" + this.getURI(predicate) + ">"); } else if (subject instanceof BlankNode) { // predicatNode representing RDF Type PredicateNode rdfTypeNode = null; try { rdfTypeNode = graph.getElementFactory().createResource(RDF.TYPE); } catch (GraphElementFactoryException factoryException) { throw new GraphException("Could not create RDF Type node.", factoryException); } // do not write the RDF Type element if (!rdfTypeNode.equals(predicate)) { // write as: <predicateURI rdf:resource="resourceURI"/> writer.println( " <" + this.getURI(predicate) + " " + RDF_PREFIX + ":resource=\"" + this.getNodeString(object) + "\"/>"); } } else { // write as: <predicateURI rdf:resource="resourceURI"/> writer.println( " <" + this.getURI(predicate) + " " + RDF_PREFIX + ":resource=\"" + this.getNodeString(object) + "\"/>"); } }
/** * Writes the opening RDF tag (with namespaces) to the print Writer. * * @param out PrintWriter * @throws IOException */ protected void writeRDFHeader(PrintWriter out) throws IOException { // validate if (out != null) { // print opening RDF tag (including namespaces) out.print("<rdf:RDF "); // print namespaces Set<String> keys = namespaces.keySet(); if (keys != null) { for (String currentKey : keys) { String currentValue = namespaces.get(currentKey); if ((currentKey != null) && (currentValue != null)) { // use entities: xmlns:ns="&ns;" out.print(NEWLINE + " xmlns:" + currentKey + "=\"&" + currentKey + ";\""); } } } // close the opening tag (add a space for readability) out.print(">" + NEWLINE + NEWLINE); } else { throw new IllegalArgumentException("Cannot write to null Writer."); } }
/** * Writes the XML Entities (used for namespaces) to the print Writer. * * @param out PrintWriter * @throws IOException */ protected void writeXMLEntities(PrintWriter out) throws IOException { // validate if (out != null) { // print opening DOCTYPE DECLARATION tag out.print(NEWLINE + "<!DOCTYPE rdf:RDF ["); // print namespaces Set<String> keys = namespaces.keySet(); if (keys != null) { for (String currentKey : keys) { String currentValue = namespaces.get(currentKey); if ((currentKey != null) && (currentValue != null)) { // write as: <!ENTITY ns 'http://example.org/abc#'> out.print(NEWLINE + " <!ENTITY " + currentKey + " '" + currentValue + "'>"); } } } // close the opening tag (add a space for readability) out.print("]>" + NEWLINE + NEWLINE); } else { throw new IllegalArgumentException("Cannot write to null Writer."); } }
/** * Writes the XML Declaration and the opening RDF tag to the print Writer. Encoding attribute is * specified as the encoding argument. * * @param out PrintWriter * @throws IOException */ protected void writeHeader(OutputStreamWriter out) throws IOException { // validate if (out != null) { // wrapper for output stream writer (enable autoflushing) PrintWriter writer = new PrintWriter(out, true); // get encoding from the Encoding map String encoding = EncodingMap.getJava2IANAMapping(out.getEncoding()); // only insert encoding if there is a value if (encoding != null) { // print opening tags <?xml version="1.0" encoding=*encoding*?> writer.println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>"); } else { // print opening tags <?xml version="1.0"?> writer.println("<?xml version=\"1.0\"?>"); } // print the Entities this.writeXMLEntities(writer); // print the opening RDF tag (including namespaces) this.writeRDFHeader(writer); } else { throw new IllegalArgumentException("Cannot write to null Writer."); } }
public static void main(String[] args) throws IOException, InterruptedException { for (int iter = 1; iter <= 1000; ++iter) { System.out.println("HELLO"); // ask for a value Socket s1 = new Socket("127.0.0.1", 12345); PrintWriter out = new PrintWriter(s1.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(s1.getInputStream())); out.println(-1); String response = in.readLine(); s1.close(); out.close(); in.close(); // increase by 1 int val = Integer.parseInt(response); val++; // set value Socket s2 = new Socket("127.0.0.1", 12345); out = new PrintWriter(s2.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(s2.getInputStream())); out.println(val); s2.close(); out.close(); in.close(); } }
/** 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(); } }
public void connect(GUIClient GUI) throws IOException { try { connectSocket = new Socket(ServerIp, ServerPort); out = new PrintWriter(connectSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(connectSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Cannot Connect to server"); // System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: " + ServerIp.toString()); // System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String clientInput = GUI.getJTareaOut().getText(); while ((clientInput = stdIn.readLine()) != null) { out.println(clientInput); System.out.println("Writing: " + in.readLine()); } out.close(); in.close(); stdIn.close(); connectSocket.close(); }
/** @param args the command line arguments */ public static void main(String[] args) { try { int randomNum = (int) ((Math.random() * 100) + 1); Socket server = new Socket("127.0.0.1", 8888); BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream())); PrintWriter output = new PrintWriter(server.getOutputStream(), true); String leggi; int total = 0; output.println(randomNum); while ((leggi = input.readLine()) != null) { System.out.println("Valore letto: " + leggi); total += Integer.parseInt(leggi); } System.out.println("Somma dei valori ricevuti dal Server: " + total); if (total % 2 == 0) { System.out.println("PARI"); } else { System.out.println("DISPARI"); } } catch (UnknownHostException ex) { System.out.println("Errore indirizzo sconosciuto:" + ex.getMessage()); } catch (IOException ex) { System.out.println(ex); } }
public static synchronized void relay(String name, String input) { PrintWriter out = null; for (OutputStream o : socketList) { out = new PrintWriter(o, true); out.println("MAIN <" + name + "> " + input); } }
public void run() { System.out.println("New Communication Thread Started"); try { PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; String[] inputTemp = new String[3]; while ((inputLine = in.readLine()) != null) { System.out.println("Server: " + inputLine); out.println(inputLine); if (inputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); } catch (IOException e) { System.err.println("Problem with Communication Server"); System.exit(1); } }
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) { } }
void writeoneline(String filename1, String filename2) throws IOException { // open the file for reading BufferedReader file = new BufferedReader(new FileReader(filename1)); String line = null; // send message System.out.println("Sending message to the server..."); while ((line = file.readLine()) != null) { String onebyone = line; output.println(onebyone); } file.close(); // open the file for reading PrintWriter file2 = new PrintWriter(new BufferedWriter(new FileWriter(filename2))); String line2 = input.readLine(); // receive a message // String response = input.readLine(); if (line2.isEmpty()) System.out.println("(server did not reply with a message)"); else { System.out.println("Writing to file...:"); // String line= null; file2.println(line2); file2.close(); } System.out.println("Done!"); }
public Server() { try { ServerSocket ss = new ServerSocket(SERVER_PORT); Socket s = ss.accept(); InputStream is = s.getInputStream(); OutputStream out = s.getOutputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String sss = br.readLine(); System.out.println(sss); PrintWriter pw = new PrintWriter(out); pw.print("hello,我是服务器。"); pw.close(); br.close(); isr.close(); out.close(); is.close(); s.close(); ss.close(); } catch (UnknownHostException ue) { ue.printStackTrace(); } catch (IOException oe) { oe.printStackTrace(); } }
private boolean write(String message) { if (socket != null) { p.println(message); p.flush(); } return true; }
@Override public void run() { // System.out.println ("New Communication Thread Started"); try { BufferedReader in; // OUTPUT STREAM try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) { in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; // READ NUMBER OF FORTUNE COOKIES CLIENT WANTS while ((inputLine = in.readLine()) != null) { // System.out.println("Hello"); if (inputLine.equals("Bye.")) break; int number = Integer.parseInt(inputLine); System.out.println("Server: " + inputLine); // SENDS RANDOMLY GENERATED COOKIES out.println(new FortuneCookies().getCookies(number)); } } // CLIENT CLOSE in.close(); clientSocket.close(); } catch (IOException e) { System.err.println("Problem with Communication Server"); System.exit(1); } }
public void go() { try { ServerSocket serverSock = new ServerSocket(4242); System.out.println(getTime() + "서버가 준비되었습니다."); // ServerSocket을 통해 이 서버 애플리케이션은 이 코드가 실행되고 있는 시스템의 4242번 포트로 들어오는 클라이언트 요청을 감시한다. while (true) { System.out.println(getTime() + "연결요청을 기다립니다."); Socket sock = serverSock.accept(); sock.setSoTimeout(2000); // accept()메소드는 요청이 들어 올때까지 그냥 기다린다. 그리고 클라이언트 요청이 들어오면 클라이언트와 통신을 위해 (현재 쓰이고 있찌 않은 포트에 대한) // Socket을 리턴함. System.out.println(getTime() + sock.getInetAddress() + "로부터 연결요청이 들어왔습니다."); PrintWriter writer = new PrintWriter(sock.getOutputStream()); String advice = getAdvice(); writer.println(advice); writer.close(); // 이제 클라이언트에 대한 Socket연결을 써서 PrintWriter를 만들고 클라이언트에 String 조언메시지를 보냄(println() 메소드 사용) // 그리고 나면 클라이언트와의 작업이 끝난 것이므로 Socket을 닫는다. System.out.println(advice); } } catch (IOException ex) { System.out.println("ssss"); ex.printStackTrace(); } } // go 메소드
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(PORT); } catch (IOException e) { System.err.println("Could not listen on port: " + PORT + "."); System.exit(1); } while (true) { Socket clientSocket = null; try { clientSocket = serverSocket.accept(); startTime = System.currentTimeMillis(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; while ((inputLine = in.readLine()) != null) { if (messageCount.get(clientSocket) == null) { messageCount.put(clientSocket, 1); } else { messageCount.put(clientSocket, messageCount.get(clientSocket) + 1); } overallMessageCount += 1; System.out.println("---------------------------------------"); System.out.println("Client: " + clientSocket.toString()); System.out.println( "aktive since " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds"); System.out.println(new Date(System.currentTimeMillis())); System.out.println("Overall Message Count: " + overallMessageCount); System.out.println("Message Count from Client: " + messageCount.get(clientSocket)); System.out.println("Message " + inputLine); System.out.println("---------------------------------------"); outputLine = inputLine.toUpperCase(); if (outputLine.equals("END")) { out.println("abort"); break; } out.println(outputLine); } out.close(); in.close(); clientSocket.close(); System.out.println("All Closed"); } // serverSocket.close(); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); System.out.println("queryString: " + request.getQueryString()); out.println("FILTER-QUERYSTRING:" + (request.getQueryString() != null ? "PASS" : "FAIL")); }
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(); }
private void sendResponse(HttpServletResponse pResp, String pContentType, String pJsonTxt) throws IOException { setContentType(pResp, pContentType); pResp.setStatus(200); setNoCacheHeaders(pResp); PrintWriter writer = pResp.getWriter(); writer.write(pJsonTxt); }