public static void main(String[] args) { ServerSocket welcomeSocket; // TCP-Server-Socketklasse Socket connectionSocket; // TCP-Standard-Socketklasse int counter = 0; // Z�hlt die erzeugten Bearbeitungs-Threads try { /* Server-Socket erzeugen */ welcomeSocket = new ServerSocket(SERVER_PORT); while (true) { // Server laufen IMMER System.out.println( "TCP Server: Waiting for connection - listening TCP port " + SERVER_PORT); /* * Blockiert auf Verbindungsanfrage warten --> nach * Verbindungsaufbau Standard-Socket erzeugen und * connectionSocket zuweisen */ connectionSocket = welcomeSocket.accept(); /* Neuen Arbeits-Thread erzeugen und den Socket �bergeben */ (new TCPServerThread(++counter, connectionSocket)).start(); } } catch (IOException e) { System.err.println(e.toString()); } }
public ByteBuffer run(Retriever retriever) { if (!retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) return null; HTTPRetriever htr = (HTTPRetriever) retriever; if (htr.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { // Mark tile as missing to avoid excessive attempts MercatorTiledImageLayer.this.levels.markResourceAbsent(tile); return null; } if (htr.getResponseCode() != HttpURLConnection.HTTP_OK) return null; URLRetriever r = (URLRetriever) retriever; ByteBuffer buffer = r.getBuffer(); String suffix = WWIO.makeSuffixForMimeType(htr.getContentType()); if (suffix == null) { return null; // TODO: log error } String path = tile.getPath().substring(0, tile.getPath().lastIndexOf(".")); path += suffix; final File outFile = WorldWind.getDataFileStore().newFile(path); if (outFile == null) return null; try { WWIO.saveBuffer(buffer, outFile); return buffer; } catch (IOException e) { e.printStackTrace(); // TODO: log error return null; } }
private void handleKeepAlive() { Connection c = null; try { netCode = ois.readInt(); c = checkConnectionNetCode(); if (c != null && c.getState() == Connection.STATE_CONNECTED) { oos.writeInt(ACK_KEEP_ALIVE); oos.flush(); System.out.println("->ACK_KEEP_ALIVE"); // $NON-NLS-1$ } else { System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$ oos.writeInt(NOT_CONNECTED); oos.flush(); } } catch (IOException e) { System.out.println("handleKeepAlive: " + e.getMessage()); // $NON-NLS-1$ if (c != null) { c.setState(Connection.STATE_DISCONNECTED); System.out.println( "Connection closed with " + c.getRemoteAddress() + //$NON-NLS-1$ ":" + c.getRemotePort()); // $NON-NLS-1$ } } }
// Send File public void sendFile(String chunkName) throws IOException { OutputStream os = null; String currentDir = System.getProperty("user.dir"); chunkName = currentDir + "/src/srcFile/" + chunkName; File myFile = new File(chunkName); byte[] arrby = new byte[(int) myFile.length()]; try { FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(arrby, 0, arrby.length); os = csocket.getOutputStream(); System.out.println("Sending File."); os.write(arrby, 0, arrby.length); os.flush(); System.out.println("File Sent."); // os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // os.close(); } }
public static String visitWeb(String urlStr) { URL url = null; HttpURLConnection httpConn = null; InputStream in = null; try { url = new URL(urlStr); httpConn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)"); in = httpConn.getInputStream(); return convertStreamToString(in); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); httpConn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } return null; }
public static void main(String[] args) { try { System.out.println("Creando socket servidor"); ServerSocket serverSocket = new ServerSocket(); System.out.println("Realizando el enlace"); InetSocketAddress addr = new InetSocketAddress("localhost", 5555); serverSocket.bind(addr); System.out.println("Aceptando conexiones"); Socket newSocket = serverSocket.accept(); System.out.println("Conexión recibida"); InputStream is = newSocket.getInputStream(); OutputStream os = newSocket.getOutputStream(); byte[] mensaje = new byte[25]; is.read(mensaje); System.out.println("Mensaje recibido: " + new String(mensaje)); System.out.println("Cerrando el nuevo socket"); newSocket.close(); System.out.println("Cerrando el socket servidor"); serverSocket.close(); System.out.println("Terminado"); } catch (IOException e) { e.printStackTrace(); } }
private boolean connectSPPMon() { if (state == ConnectionEvent.CONNECTION_PENDING) { ExpCoordinator.print( new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0); while (state == ConnectionEvent.CONNECTION_PENDING) { try { Thread.sleep(500); } catch (java.lang.InterruptedException e) { } } return (isConnected()); } state = ConnectionEvent.CONNECTION_PENDING; if (nonProxy != null) { try { nonProxy.connect(); } catch (UnknownHostException e) { boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage()); return rtn; } catch (SocketTimeoutException e) { boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage()); return rtn; } catch (IOException e) { boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage()); return rtn; } } return (isConnected()); }
public timeReader() { try { time = new BufferedReader(new InputStreamReader(socketForTime.getInputStream())); } catch (IOException e) { e.printStackTrace(); } }
public void run() { try { boolean connected = true; System.out.println("a client has connected!"); dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); while (connected) { int cid = clients.indexOf(this) + 1; try { String str = dis.readUTF(); System.out.println(str); for (int i = 0; i < clients.size(); i++) { clients.get(i).dos.writeUTF("Client" + cid + ":" + str); } } catch (IOException e) { connected = false; } } dis.close(); dos.close(); s.close(); clients.remove(this); System.out.println("a client is qiut!"); } catch (IOException e) { e.printStackTrace(); } }
private Class<?> findClassInComponents(final String name) throws ClassNotFoundException { final String classFilename = this.getClassFilename(name); final Enumeration<File> e = this.pathComponents.elements(); while (e.hasMoreElements()) { final File pathComponent = e.nextElement(); InputStream stream = null; try { stream = this.getResourceStream(pathComponent, classFilename); if (stream != null) { this.log("Loaded from " + pathComponent + " " + classFilename, 4); return this.getClassFromStream(stream, name, pathComponent); } continue; } catch (SecurityException se) { throw se; } catch (IOException ioe) { this.log( "Exception reading component " + pathComponent + " (reason: " + ioe.getMessage() + ")", 3); } finally { FileUtils.close(stream); } } throw new ClassNotFoundException(name); }
public carReturned() { try { OISforLot = new ObjectInputStream(socketForParkingLot.getInputStream()); } catch (IOException e) { e.printStackTrace(); } }
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 ensureExists(File thing, String resource) { System.err.println("configfile = " + thing); if (!thing.exists()) { try { System.err.println("Creating: " + thing + " from " + resource); if (resource.indexOf("/") != 0) { resource = "/" + resource; } InputStream is = Config.class.getResourceAsStream(resource); if (is == null) { throw new NullPointerException("Can't find resource: " + resource); } getParentFile(thing).mkdirs(); OutputStream os = new FileOutputStream(thing); for (int next = is.read(); next != -1; next = is.read()) { os.write(next); } os.flush(); os.close(); } catch (FileNotFoundException fnfe) { throw new Error("Can't create resource: " + fnfe.getMessage()); } catch (IOException ioe) { throw new Error("Can't create resource: " + ioe.getMessage()); } } }
public void run() { String capitalizedSentence; System.out.println("TCP Server Thread " + name + " is running until QUIT is received!"); try { /* Socket-Basisstreams durch spezielle Streams filtern */ inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); outToClient = new DataOutputStream(socket.getOutputStream()); while (serviceRequested) { /* String vom Client empfangen und in Gro�buchstaben umwandeln */ capitalizedSentence = readFromClient().toUpperCase(); /* Modifizierten String an Client senden */ writeToClient(capitalizedSentence); /* Test, ob Arbeitsthread beendet werden soll */ if (capitalizedSentence.indexOf("QUIT") > -1) { serviceRequested = false; } } /* Socket-Streams schlie�en --> Verbindungsabbau */ socket.close(); } catch (IOException e) { System.err.println(e.toString()); System.exit(1); } System.out.println("TCP Server Thread " + name + " stopped!"); }
public static void main(String[] args) { try { Socket s1 = new Socket("127.0.0.1", 57643); InputStream is = s1.getInputStream(); DataInputStream dis = new DataInputStream(is); System.out.println(dis.readUTF()); OutputStream os = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); dos.writeUTF("Oh my gosh..."); dis.close(); is.close(); dos.close(); os.close(); s1.close(); } catch (ConnectException connExc) { connExc.printStackTrace(); System.out.println("Server connection failed"); } catch (IOException ioExc) { ioExc.printStackTrace(); } }
/** Kills the receiver and ends the connection. Should also be performed before exiting. */ public void kill() { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } }
// прочитать весь json в строку private static String readAll() throws IOException { StringBuilder data = new StringBuilder(); try { HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("GET"); con.setDoInput(true); String s; try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { while ((s = in.readLine()) != null) { data.append(s); } } } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc."); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot read from server"); } return data.toString(); }
/** * Create an Archival Unit * * @return true If successful */ private boolean createAu() { Configuration config = getAuConfigFromForm(); AuProxy au; Element element; try { au = getRemoteApi().createAndSaveAuConfiguration(getPlugin(), config); } catch (ArchivalUnit.ConfigurationException exception) { return error("Configuration failed: " + exception.getMessage()); } catch (IOException exception) { return error("Unable to save configuration: " + exception.getMessage()); } /* * Successful creation - add the AU name and ID to the response document */ element = getXmlUtils().createElement(getResponseRoot(), AP_E_AU); XmlUtils.addText(element, au.getName()); element = getXmlUtils().createElement(getResponseRoot(), AP_E_AUID); XmlUtils.addText(element, au.getAuId()); return true; }
public void run() { try { theInputStream = new BufferedReader(new InputStreamReader(client.getInputStream())); theOutputStream = new PrintStream(client.getOutputStream()); while (true) { readin = theInputStream.readLine(); chat.ta.append(readin + "\n"); } } catch (SocketException e) { chat.ta.append("连接中断!\n"); chat.clientBtn.setEnabled(true); chat.serverBtn.setEnabled(true); chat.tfaddress.setEnabled(true); chat.tfport.setEnabled(true); try { i--; skt.close(); client.close(); } catch (IOException err) { chat.ta.append(err.toString()); } } catch (IOException e) { chat.ta.append(e.toString()); } }
private void server() { new CountDown(60).start(); while (true) { try { Socket socket = serverSock.accept(); System.out.println("New Client:" + socket); if (readyState[6] == 1) { System.out.println("正在游戏中,无法加入"); continue; } for (i = 0; i <= 5; i++) { if (players[i].equals("虚位以待")) break; } if (i > 5) { System.out.println("房间已满,无法加入"); continue; } i++; ObjectOutputStream remoteOut = new ObjectOutputStream(socket.getOutputStream()); clients.addElement(remoteOut); ObjectInputStream remoteIn = new ObjectInputStream(socket.getInputStream()); new ServerHelder(remoteIn, remoteOut, socket.getPort(), i).start(); } catch (IOException e) { System.out.println(e.getMessage() + ": Failed to connect to client."); try { serverSock.close(); } catch (IOException x) { System.out.println(e.getMessage() + ": Failed to close server socket."); } } } }
private void readProblemInfo(String pathName) { ProblemManager problemManager = new ProblemManager(); File file = new File(pathName); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { String[] sp = line.split(","); String input = MyUtil.readFromFile(new File(sp[1])); String output = MyUtil.readFromFile(new File(sp[2])); int timeLimit = Integer.valueOf(sp[3]); int memoryLimit = Integer.valueOf(sp[4]); String judgeMethod = ""; if (sp.length == 6) judgeMethod = MyUtil.readFromFile(new File(sp[5])); Map<String, String> pinfo = new HashMap<String, String>(); this.problems.put(sp[0], new ProblemInfo(sp[0], timeLimit, memoryLimit, 0)); pinfo.put("problem_id", sp[0]); pinfo.put("time_limit", String.valueOf(timeLimit)); pinfo.put("memory_limit", String.valueOf(memoryLimit)); pinfo.put("special_judge", judgeMethod); pinfo.put("input", input); pinfo.put("output", output); pinfo.put("time_stamp", "0"); problemManager.addEntry(pinfo); } } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
public HttpReport(QAT parent, String urlString, String baseDir, StatusWindow status) { // check if the basedir exists if (!(new File(baseDir).exists())) { String message = "Error - cannot generate report, directory does not exist:" + baseDir; if (status == null) { System.out.println(message); } else { status.setMessage(message); } return; } this.parent = parent; this.status = status; processedLinks = new ArrayList(); try { processURL(new URL(urlString), baseDir, status); writeDeadLinks(baseDir); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { processedLinks.clear(); } }
/** * Creates new HTTP requests handler. * * @param hnd Handler. * @param authChecker Authentication checking closure. * @param log Logger. */ GridJettyRestHandler( GridRestProtocolHandler hnd, GridClosure<String, Boolean> authChecker, GridLogger log) { assert hnd != null; assert log != null; this.hnd = hnd; this.log = log; this.authChecker = authChecker; // Init default page and favicon. try { initDefaultPage(); if (log.isDebugEnabled()) log.debug("Initialized default page."); } catch (IOException e) { U.warn(log, "Failed to initialize default page: " + e.getMessage()); } try { initFavicon(); if (log.isDebugEnabled()) log.debug( favicon != null ? "Initialized favicon, size: " + favicon.length : "Favicon is null."); } catch (IOException e) { U.warn(log, "Failed to initialize favicon: " + e.getMessage()); } }
public void run() { byte[] tmp = new byte[10000]; int read; try { FileInputStream fis = new FileInputStream(fileToSend.getFile()); read = fis.read(tmp); while (read != -1) { baos.write(tmp, 0, read); read = fis.read(tmp); System.out.println(read); } fis.close(); baos.writeTo(sWriter); sWriter.flush(); baos.flush(); baos.close(); System.out.println("fileSent"); } catch (IOException e) { e.printStackTrace(); } finally { this.closeSocket(); } }
public void run() { System.out.println("ExeUDPServer开始监听..." + UDP_PORT); DatagramSocket ds = null; try { ds = new DatagramSocket(UDP_PORT); } catch (BindException e) { System.out.println("UDP端口使用中...请重关闭程序启服务器"); } catch (SocketException e) { e.printStackTrace(); } while (ds != null) { DatagramPacket dp = new DatagramPacket(buf, buf.length); try { ds.receive(dp); // 得到把该数据包发来的端口和Ip int rport = dp.getPort(); InetAddress addr = dp.getAddress(); String recvStr = new String(dp.getData(), 0, dp.getLength()); System.out.println("Server receive:" + recvStr + " from " + addr + " " + rport); // 给客户端回应 String sendStr = "echo of " + recvStr; byte[] sendBuf; sendBuf = sendStr.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, rport); ds.send(sendPacket); } catch (IOException e) { e.printStackTrace(); } } }
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(); } }
public void run() { while (moreQuotes) { try { byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // containing IP ecc. // figure out response String dString = null; if (in == null) dString = new Date().toString(); else dString = getNextQuote(); buf = dString.getBytes(); // send the response to the client at "address" and "port" InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } catch (IOException e) { e.printStackTrace(); moreQuotes = false; } } socket.close(); }
/** * Save onscreen image to file - suffix must be png, jpg, or gif. * * @param filename the name of the file with one of the required suffixes */ public static void save(String filename) { File file = new File(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); // png files if (suffix.toLowerCase().equals("png")) { try { ImageIO.write(onscreenImage, suffix, file); } catch (IOException e) { e.printStackTrace(); } } // need to change from ARGB to RGB for jpeg // reference: // http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727 else if (suffix.toLowerCase().equals("jpg")) { WritableRaster raster = onscreenImage.getRaster(); WritableRaster newRaster; newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2}); DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel(); DirectColorModel newCM = new DirectColorModel( cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask()); BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null); try { ImageIO.write(rgbBuffer, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Invalid image file type: " + suffix); } }
/** * compare the byte-array representation of two TaskObjects. * * @param f TaskObject * @param s TaskObject * @return true if the two arguments have the same byte-array */ private boolean sameBytes(TaskObject f, TaskObject s) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(f); byte[] fs = bos.toByteArray(); out.writeObject(s); byte[] ss = bos.toByteArray(); if (fs.length != ss.length) return false; for (int i = 0; i < fs.length; i++) { if (fs[i] != ss[i]) return false; } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { // ignore } try { bos.close(); } catch (IOException e) { // ignore } } } }
public void copyFile(String file1, String file2) { InputStream inStream = null; OutputStream outStream = null; try { File afile = new File(file1); File bfile = new File(file2); inStream = new FileInputStream(afile); outStream = new FileOutputStream(bfile); byte[] buffer = new byte[1024]; int length; // copy the file content in bytes while ((length = inStream.read(buffer)) > 0) { outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); System.out.println("File is copied successful!"); } catch (IOException e) { e.printStackTrace(); } }