/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); for (int i = 0; i < 10; i++) { sslOS.write(280); sslOS.flush(); sslIS.read(); } for (int i = 0; i < 10; i++) { sslOS.write(280); sslOS.flush(); sslIS.read(); } sslSocket.close(); }
private boolean userPassAuth() throws IOException { int ver = in.read(); int ulen = in.read(); if (ulen <= 0) throw new SocketException("SOCKS protocol error"); byte[] buf = new byte[ulen]; readBuf(in, buf); String uname = new String(buf); String password = null; ulen = in.read(); if (ulen < 0) throw new SocketException("SOCKS protocol error"); if (ulen > 0) { buf = new byte[ulen]; readBuf(in, buf); password = new String(buf); } // Check username/password validity here System.err.println("User: '******'" + password); if (users.containsKey(uname)) { String p1 = users.get(uname); System.err.println("p1 = " + p1); if (p1.equals(password)) { out.write(PROTO_VERS); out.write(REQUEST_OK); out.flush(); return true; } } out.write(PROTO_VERS); out.write(NOT_ALLOWED); out.flush(); return false; }
private void passTcpFileDescriptor( LocalSocket fdSocket, OutputStream outputStream, String socketId, String dstIp, int dstPort, int connectTimeout) throws Exception { Socket sock = new Socket(); sock.setTcpNoDelay(true); // force file descriptor being created if (protect(sock)) { try { sock.connect(new InetSocketAddress(dstIp, dstPort), connectTimeout); ParcelFileDescriptor fd = ParcelFileDescriptor.fromSocket(sock); tcpSockets.put(socketId, sock); fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()}); outputStream.write('*'); outputStream.flush(); fd.detachFd(); } catch (ConnectException e) { LogUtils.e("connect " + dstIp + ":" + dstPort + " failed"); outputStream.write('!'); sock.close(); } catch (SocketTimeoutException e) { LogUtils.e("connect " + dstIp + ":" + dstPort + " failed"); outputStream.write('!'); sock.close(); } finally { outputStream.flush(); } } else { LogUtils.e("protect tcp socket failed"); } }
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()); } } }
// 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(); } }
/** * ** Writes the specified byte array to the specified socket's output stream ** @param socket The * socket which's output stream to write to ** @param b The byte array to write to the socket * output stream ** @throws IOException if an error occurs */ protected static void socketWriteBytes(Socket socket, byte b[]) throws IOException { if ((socket != null) && (b != null)) { OutputStream output = socket.getOutputStream(); output.write(b); output.flush(); } }
public static void main(String args[]) throws Exception { int count = 0; ServerSocket serv = null; InputStream in = null; OutputStream out = null; Socket sock = null; int clientId = 0; Map<Integer, Integer> totals = new HashMap<Integer, Integer>(); try { serv = new ServerSocket(8888); } catch (Exception e) { e.printStackTrace(); } while (serv.isBound() && !serv.isClosed()) { System.out.println("Ready..."); try { sock = serv.accept(); in = sock.getInputStream(); out = sock.getOutputStream(); char c = (char) in.read(); System.out.print("Server received " + c); switch (c) { case 'r': clientId = in.read(); totals.put(clientId, 0); out.write(0); break; case 't': clientId = in.read(); int x = in.read(); System.out.print(" for client " + clientId + " " + x); Integer total = totals.get(clientId); if (total == null) { total = 0; } totals.put(clientId, total + x); out.write(totals.get(clientId)); break; default: int x2 = in.read(); int y = in.read(); System.out.print(" " + x2 + " " + y); out.write(x2 + y); } System.out.println(""); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) out.close(); if (in != null) in.close(); if (sock != null) sock.close(); } } }
private void doBind(InetSocketAddress addr) throws IOException { ServerSocket svr = new ServerSocket(); svr.bind(null); InetSocketAddress bad = (InetSocketAddress) svr.getLocalSocketAddress(); out.write(PROTO_VERS); out.write(REQUEST_OK); out.write(0); out.write(IPV4); out.write(bad.getAddress().getAddress()); out.write((bad.getPort() >> 8) & 0xff); out.write((bad.getPort() & 0xff)); out.flush(); dest = svr.accept(); bad = (InetSocketAddress) dest.getRemoteSocketAddress(); out.write(PROTO_VERS); out.write(REQUEST_OK); out.write(0); out.write(IPV4); out.write(bad.getAddress().getAddress()); out.write((bad.getPort() >> 8) & 0xff); out.write((bad.getPort() & 0xff)); out.flush(); InputStream in2 = dest.getInputStream(); OutputStream out2 = dest.getOutputStream(); Tunnel tunnel = new Tunnel(in2, out); tunnel.start(); int b = 0; do { // Note that the socket might be close from another thread (the tunnel) try { b = in.read(); if (b == -1) { in.close(); out2.close(); return; } out2.write(b); } catch (IOException ioe) { } } while (!client.isClosed()); }
/** * ** Writes <code>length</code> bytes from the specified byte array ** starting at <code>offset * </code> to the specified socket's output stream. ** @param socket The socket which's output * stream to write to ** @param b The byte array to write to the socket output stream ** @param * offset The start offset in the data to begin writing at ** @param length The length of the * data. Normally <code>b.length</code> ** @throws IOException if an error occurs */ protected static void socketWriteBytes(Socket socket, byte b[], int offset, int length) throws IOException { if ((socket != null) && (b != null)) { int bofs = offset; int blen = (length >= 0) ? length : b.length; OutputStream output = socket.getOutputStream(); output.write(b, bofs, blen); output.flush(); } }
private void doConnect(InetSocketAddress addr) throws IOException { dest = new Socket(); try { dest.connect(addr, 10000); } catch (SocketTimeoutException ex) { sendError(HOST_UNREACHABLE); return; } catch (ConnectException cex) { sendError(CONN_REFUSED); return; } // Success InetAddress iadd = addr.getAddress(); if (iadd instanceof Inet4Address) { out.write(PROTO_VERS); out.write(REQUEST_OK); out.write(0); out.write(IPV4); out.write(iadd.getAddress()); } else if (iadd instanceof Inet6Address) { out.write(PROTO_VERS); out.write(REQUEST_OK); out.write(0); out.write(IPV6); out.write(iadd.getAddress()); } else { sendError(GENERAL_FAILURE); return; } out.write((addr.getPort() >> 8) & 0xff); out.write((addr.getPort() >> 0) & 0xff); out.flush(); InputStream in2 = dest.getInputStream(); OutputStream out2 = dest.getOutputStream(); Tunnel tunnel = new Tunnel(in2, out); tunnel.start(); int b = 0; do { // Note that the socket might be closed from another thread (the tunnel) try { b = in.read(); if (b == -1) { in.close(); out2.close(); return; } out2.write(b); } catch (IOException ioe) { } } while (!client.isClosed()); }
public void send(ByteArrayInputStream sendBytes) throws SocketException { // A byte array representing a data packet byte[] packet; // While there are more than 127 bytes still to send ... while (sendBytes.available() > 127) { // ... create a 128 byte packet, ... packet = new byte[128]; // ... set the header to 255, ... packet[0] = (byte) 255; // ... read 127 bytes from the sequence of bytes to send, ... sendBytes.read(packet, 1, 127); // ... and send the packet to the external process. try { output.write(packet); output.flush(); } catch (IOException e) { e.printStackTrace(); } } // Create a packet for any remaining data packet = new byte[sendBytes.available() + 1]; // Set the header appropriately packet[0] = (byte) (sendBytes.available()); // Read the remaining bytes into the packet sendBytes.read(packet, 1, sendBytes.available()); // Send the packet to the external process try { output.write(packet); output.flush(); } catch (IOException e) { e.printStackTrace(); } }
void doTest(SSLSocket sslSocket) throws Exception { InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); System.out.println(" Writing"); sslOS.write(280); sslOS.flush(); System.out.println(" Reading"); sslIS.read(); sslSocket.close(); }
// Send error message then close the streams private void sendError(int code) { try { out.write(PROTO_VERS); out.write(code); out.write(0); out.write(IPV4); for (int i = 0; i < 6; i++) out.write(0); out.flush(); out.close(); } catch (IOException ex) { } }
public int writePacket(JICPPacket pkt) throws IOException { if (sc != null) { if (os == null) { os = getOutputStream(); } int ret = pkt.writeTo(os); os.flush(); return ret; } else { throw new IOException("Connection closed"); } }
/** * A private function to write things out. This needs to be syncrhonized as writes can occur from * multiple threads. We write in chunks to allow the other side to synchronize for large sized * writes. */ private void writeChunks(OutputStream outputStream, byte[] bytes, int length) throws IOException { // Chunk size is 16K - this hack is for large // writes over slow connections. synchronized (outputStream) { // outputStream.write(bytes,0,length); int chunksize = 8 * 1024; for (int p = 0; p < length; p += chunksize) { int chunk = p + chunksize < length ? chunksize : length - p; outputStream.write(bytes, p, chunk); } } outputStream.flush(); }
private void passUdpFileDescriptor( LocalSocket fdSocket, OutputStream outputStream, String socketId) throws Exception { DatagramSocket sock = new DatagramSocket(); if (protect(sock)) { ParcelFileDescriptor fd = ParcelFileDescriptor.fromDatagramSocket(sock); udpSockets.put(socketId, sock); fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()}); outputStream.write('*'); outputStream.flush(); fd.detachFd(); } else { LogUtils.e("protect udp socket failed"); } }
// Negociate the authentication scheme with the client private void negociate() throws IOException { int ver = in.read(); int n = in.read(); byte[] buf = null; if (n > 0) { buf = new byte[n]; readBuf(in, buf); } int scheme = NO_AUTH; for (int i = 0; i < n; i++) if (buf[i] == USER_PASSW) scheme = USER_PASSW; out.write(PROTO_VERS); out.write(scheme); out.flush(); if (scheme == USER_PASSW) userPassAuth(); }
/* * Define the server side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doServerSide() throws Exception { SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort); serverPort = sslServerSocket.getLocalPort(); /* * Signal Client, we're ready for his connect. */ serverReady = true; SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); sslSocket.addHandshakeCompletedListener(this); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); for (int i = 0; i < 10; i++) { sslIS.read(); sslOS.write(85); sslOS.flush(); } System.out.println("invalidating"); sslSocket.getSession().invalidate(); System.out.println("starting new handshake"); sslSocket.startHandshake(); for (int i = 0; i < 10; i++) { System.out.println("sending/receiving data, iteration: " + i); sslIS.read(); sslOS.write(85); sslOS.flush(); } sslSocket.close(); }
void sendRequest(InputStream in, OutputStream out) throws IOException { out.write("GET / HTTP/1.0\r\n\r\n".getBytes()); out.flush(); StringBuilder sb = new StringBuilder(); while (true) { int ch = in.read(); if (ch < 0) { break; } sb.append((char) ch); } String response = sb.toString(); if (response.startsWith("HTTP/1.0 200 ") == false) { throw new IOException("Invalid response: " + response); } }
private void nextRunAge(long minAge, HttpServletResponse response) throws IOException { NameValuePair<Long> runAge = RunQ.getHandle().nextRunAge(minAge); if (runAge == null) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } StringBuilder output = new StringBuilder(128); output.append(runAge.name).append('\t').append(runAge.value); response.setContentType("txt/plain"); response.setStatus(HttpServletResponse.SC_OK); OutputStream out = response.getOutputStream(); out.write(output.toString().getBytes()); out.flush(); out.close(); }
public void run() { try { sc = new Socket(); InetSocketAddress isa = new InetSocketAddress("localhost", 9999); sc.connect(isa); OutputStream ost = sc.getOutputStream(); for (int i = 0; i < 10; ++i) { String str = "client interation " + (new Integer(i)).toString(); ost.write(str.getBytes()); ost.flush(); System.out.println("Client at " + (new Integer(i)).toString()); sleep(1000); } } catch (Exception e) { } }
public int sendChunk(OutputStream output, int chunkId) throws IOException { String path = "D:\\CN Project\\Client\\Client" + id + "\\" + chunkId; FileInputStream in = new FileInputStream(path); byte[] data_send = null; int count = 0; if (chunkId + 1 == noOfChunks) { data_send = new byte[bytesInLastChunk]; while (count < bytesInLastChunk) count += in.read(data_send, count, bytesInLastChunk - count); } else { data_send = new byte[102400]; while (count < 102400) count += in.read(data_send, count, 102400 - count); } output.write(data_send); output.flush(); in.close(); return 0; }
/* * Define the server side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ static void doServerSide() throws Exception { ServerSocket serverSocket = new ServerSocket(serverPort); serverPort = serverSocket.getLocalPort(); /* * Signal Client, we're ready for a connect. */ serverReady = true; Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); os.write(85); os.flush(); socket.close(); }
private void fetchNextRun(String runId, HttpServletResponse response) throws IOException, ClassNotFoundException { Run nextRun = null; for (; ; ) try { nextRun = RunQ.getHandle().fetchNextRun(runId); break; } catch (RunEntryException e) { } if (nextRun == null) { // Queue empty logger.warning("Fetching run " + runId + ": No longer available!"); response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } // Jar up the run. File jarFile = null; jarFile = jar(nextRun); // Send the run jar to the output stream long length = jarFile.length(); int bufferSize = 1024 * 1024 * 128; // 128MB buffer limit if (length < bufferSize) bufferSize = (int) length; byte[] buffer = new byte[bufferSize]; response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/java-archive"); OutputStream out = response.getOutputStream(); FileInputStream jarIn = new FileInputStream(jarFile); int readSize = 0; while ((readSize = jarIn.read(buffer)) != -1) out.write(buffer, 0, readSize); out.flush(); out.close(); // Update status locally nextRun.updateStatus(Run.RECEIVED); // Clear tmp file jarFile.delete(); }
public void sendResponseHeaders(int rCode, long contentLen) throws IOException { if (sentHeaders) { throw new IOException("headers already sent"); } this.rcode = rCode; String statusLine = "HTTP/1.1 " + rCode + Code.msg(rCode) + "\r\n"; OutputStream tmpout = new BufferedOutputStream(ros); PlaceholderOutputStream o = getPlaceholderResponseBody(); tmpout.write(bytes(statusLine, 0), 0, statusLine.length()); boolean noContentToSend = false; // assume there is content rspHdrs.set("Date", df.format(new Date())); if (contentLen == 0) { if (http10) { o.setWrappedStream(new UndefLengthOutputStream(this, ros)); close = true; } else { rspHdrs.set("Transfer-encoding", "chunked"); o.setWrappedStream(new ChunkedOutputStream(this, ros)); } } else { if (contentLen == -1) { noContentToSend = true; contentLen = 0; } /* content len might already be set, eg to implement HEAD resp */ if (rspHdrs.getFirst("Content-length") == null) { rspHdrs.set("Content-length", Long.toString(contentLen)); } o.setWrappedStream(new FixedLengthOutputStream(this, ros, contentLen)); } write(rspHdrs, tmpout); this.rspContentLen = contentLen; tmpout.flush(); tmpout = null; sentHeaders = true; if (noContentToSend) { WriteFinishedEvent e = new WriteFinishedEvent(this); server.addEvent(e); closed = true; } server.logReply(rCode, req.requestLine(), null); }
/** * Watches an event. * * @param name event name * @param notifier event notification * @throws IOException I/O exception */ public void watch(final String name, final EventNotifier notifier) throws IOException { out.write(10); if (esocket == null) { final int eport = Integer.parseInt(receive()); // initialize event socket esocket = new Socket(); esocket.connect(new InetSocketAddress(ehost, eport), 5000); final OutputStream os = esocket.getOutputStream(); receive(in, os); os.write(0); os.flush(); final InputStream is = esocket.getInputStream(); is.read(); listen(is); } send(name); info = receive(); if (!ok()) throw new IOException(info); notifiers.put(name, notifier); }
public void run() { try { Socket s = serverSock.accept(); InputStream in = s.getInputStream(); byte b[] = new byte[4096]; // assume we read the entire http request // (bad assumption but okay for test case) int nread = in.read(b); // check the date format by the position of the comma String request = new String(b, 0, nread); int pos = request.indexOf("If-Modified-Since:"); int respCode = 200; if (pos != -1) { pos += "If-Modified-Since:".length() + 4; if (pos < nread) { if (request.charAt(pos) == (char) ',') { respCode = 304; } } } OutputStream o = s.getOutputStream(); if (respCode == 304) { o.write("HTTP/1.1 304 Not Modified".getBytes()); } else { o.write("HTTP/1.1 200 OK".getBytes()); } o.write((byte) '\r'); o.write((byte) '\n'); o.write((byte) '\r'); o.write((byte) '\n'); o.flush(); } catch (Exception e) { } }
/** * Watches an event. * * @param name event name * @param notifier event notification * @throws IOException I/O exception */ public void watch(final String name, final EventNotifier notifier) throws IOException { sout.write(ServerCmd.WATCH.code); if (esocket == null) { sout.flush(); final BufferInput bi = new BufferInput(sin); final int eport = Integer.parseInt(bi.readString()); // initialize event socket esocket = new Socket(); esocket.connect(new InetSocketAddress(ehost, eport), 5000); final OutputStream so = esocket.getOutputStream(); so.write(bi.readBytes()); so.write(0); so.flush(); final InputStream is = esocket.getInputStream(); is.read(); listen(is); } send(name); sout.flush(); receive(null); notifiers.put(name, notifier); }
public void run() { try { sleep(5000); int i = 0; while (true) { System.out.println("服务器发命令00000000000000!!"); os = s.getOutputStream(); System.out.println("服务器发命令!!"); // if(i==0) // os.write("CMD_OPENSESSION:192.168.1.12,2555;".getBytes()); if (i == 1) os.write("CMD_STARTMONITOR:8912;".getBytes()); if (i == 2) os.write("CMD_STARTMONITOR:8913;".getBytes()); //// CMD_MAKECALL:beginport,otherNum; if (i == 3) { os.write("CMD_MAKECALL:8912,8913;".getBytes()); } if (i == 4) { os.write("CMD_STOPMONITOR:8912;".getBytes()); } if (i == 5) { os.write("CMD_STOPMONITOR:8913;".getBytes()); } if (i == 6) { os.write("CMD_CLOSESESSION:;".getBytes()); } System.out.println(i); i++; os.flush(); sleep(3000); } } catch (Exception e) { e.printStackTrace(); } }
public void flush() throws IOException { checkWrap(); wrapped.flush(); }