public static void main(String args[]) throws IOException { ServerSocket sSocket = new ServerSocket(sPort, 10); // Arguments Handling if (args.length != 1) { System.out.println("Must specify a file-path argument."); } else { String currentDir = System.getProperty("user.dir"); filePath = currentDir + "/src/srcFile/" + args[0]; filename = args[0]; } // Get list of chunks owned chunkOwned(); // Call FileSplitter FileSplitter fs = new FileSplitter(); fs.split(filePath); System.out.println("Waiting for connection"); while (true) { Socket connection = sSocket.accept(); System.out.println("Connection received from " + connection.getInetAddress().getHostName()); new Thread(new MultiThreadServer(connection)).start(); } }
SelectableChannel doConnect() throws IOException, InterruptedException { final ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.socket().setReceiveBufferSize(BUFFER_SIZE); serverChannel.configureBlocking(false); final ServerSocket serverSocket = serverChannel.socket(); serverSocket.setReuseAddress(true); serverSocket.bind(details.address()); // these can be run on this thread addPendingRegistration( new Runnable() { @Override public void run() { final Attached attached = new Attached(); attached.connector = ServerConnector.this; try { serverChannel.register(TcpReplicator.this.selector, OP_ACCEPT, attached); } catch (ClosedChannelException e) { LOG.error("", e); } } }); selector.wakeup(); return serverChannel; }
public void run() { try { SocketChannel sc = SocketChannel.open(); InetSocketAddress sinaAddr = new InetSocketAddress("sina.com", 80); sc.socket().connect(sinaAddr); // init a selector via helper class selector provider Selector aSel = SelectorProvider.provider().openSelector(); Socket soc = new Socket("host", 80); soc.getChannel().register(aSel, SelectionKey.OP_ACCEPT); // init a channel for server socket. method 1 ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(true); // method 2, get server socket first, then init its channel ServerSocket ss = new ServerSocket(); ServerSocketChannel ssc2 = ss.getChannel(); // set socket channel as non blocking. ssc.configureBlocking(false); InetSocketAddress isa = new InetSocketAddress("localhost", 9999); ssc.socket().bind(isa); SelectionKey acceptKey = ssc.register(aSel, SelectionKey.OP_ACCEPT); int keysAdded = 0; while ((keysAdded = aSel.select()) > 0) { Set readyKeys = aSel.selectedKeys(); Iterator i = readyKeys.iterator(); while (i.hasNext()) { SelectionKey sk = (SelectionKey) i.next(); i.remove(); ServerSocketChannel n = (ServerSocketChannel) sk.channel(); // now we got a new socket and its channel after accept in server Socket s = n.accept().socket(); SocketChannel socketChannel = s.getChannel(); socketChannel.register(aSel, SelectionKey.OP_READ); } } } catch (Exception e) { } }
public void listen(EndPoint localEp, boolean isHttp) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); ServerSocket ss = serverChannel.socket(); ss.bind(localEp.getInetAddress()); serverChannel.configureBlocking(false); SelectionKeyHandler handler = null; if (isHttp) { handler = new HttpConnectionHandler(); } else { handler = new TcpConnectionHandler(localEp); } SelectionKey key = SelectorManager.getSelectorManager() .register(serverChannel, handler, SelectionKey.OP_ACCEPT); endPoints_.add(localEp); listenSockets_.put(localEp, key); }
/** {@inheritDoc} */ @Override public void start() throws IgniteCheckedException { IpcSharedMemoryNativeLoader.load(log); pid = IpcSharedMemoryUtils.pid(); if (pid == -1) throw new IpcEndpointBindException("Failed to get PID of the current process."); if (size <= 0) throw new IpcEndpointBindException("Space size should be positive: " + size); String tokDirPath = this.tokDirPath; if (F.isEmpty(tokDirPath)) throw new IpcEndpointBindException("Token directory path is empty."); tokDirPath = tokDirPath + '/' + locNodeId.toString() + '-' + IpcSharedMemoryUtils.pid(); tokDir = U.resolveWorkDirectory(tokDirPath, false); if (port <= 0 || port >= 0xffff) throw new IpcEndpointBindException("Port value is illegal: " + port); try { srvSock = new ServerSocket(); // Always bind to loopback. srvSock.bind(new InetSocketAddress("127.0.0.1", port)); } catch (IOException e) { // Although empty socket constructor never throws exception, close it just in case. U.closeQuiet(srvSock); throw new IpcEndpointBindException( "Failed to bind shared memory IPC endpoint (is port already " + "in use?): " + port, e); } gcWorker = new GcWorker(gridName, "ipc-shmem-gc", log); new IgniteThread(gcWorker).start(); if (log.isInfoEnabled()) log.info( "IPC shared memory server endpoint started [port=" + port + ", tokDir=" + tokDir.getAbsolutePath() + ']'); }
private void go() throws IOException { // Create a new selector Selector selector = Selector.open(); // Open a listener on each port, and register each one // with the selector for (int i = 0; i < ports.length; ++i) { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ServerSocket ss = ssc.socket(); InetSocketAddress address = new InetSocketAddress(ports[i]); ss.bind(address); SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Going to listen on " + ports[i]); } while (true) { int num = selector.select(); Set selectedKeys = selector.selectedKeys(); Iterator it = selectedKeys.iterator(); while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { // Accept the new connection ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); // Add the new connection to the selector SelectionKey newKey = sc.register(selector, SelectionKey.OP_READ); it.remove(); System.out.println("Got connection from " + sc); } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // Read the data SocketChannel sc = (SocketChannel) key.channel(); // Echo data int bytesEchoed = 0; while (true) { echoBuffer.clear(); int r = sc.read(echoBuffer); if (r <= 0) { break; } echoBuffer.flip(); sc.write(echoBuffer); bytesEchoed += r; } System.out.println("Echoed " + bytesEchoed + " from " + sc); it.remove(); } } // System.out.println( "going to clear" ); // selectedKeys.clear(); // System.out.println( "cleared" ); } }
/** {@inheritDoc} */ @SuppressWarnings("ErrorNotRethrown") @Override public IpcEndpoint accept() throws IgniteCheckedException { while (!Thread.currentThread().isInterrupted()) { Socket sock = null; boolean accepted = false; try { sock = srvSock.accept(); accepted = true; InputStream inputStream = sock.getInputStream(); ObjectInputStream in = new ObjectInputStream(inputStream); ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream()); IpcSharedMemorySpace inSpace = null; IpcSharedMemorySpace outSpace = null; boolean err = true; try { IpcSharedMemoryInitRequest req = (IpcSharedMemoryInitRequest) in.readObject(); if (log.isDebugEnabled()) log.debug("Processing request: " + req); IgnitePair<String> p = inOutToken(req.pid(), size); String file1 = p.get1(); String file2 = p.get2(); assert file1 != null; assert file2 != null; // Create tokens. new File(file1).createNewFile(); new File(file2).createNewFile(); if (log.isDebugEnabled()) log.debug("Created token files: " + p); inSpace = new IpcSharedMemorySpace(file1, req.pid(), pid, size, true, log); outSpace = new IpcSharedMemorySpace(file2, pid, req.pid(), size, false, log); IpcSharedMemoryClientEndpoint ret = new IpcSharedMemoryClientEndpoint(inSpace, outSpace, log); out.writeObject( new IpcSharedMemoryInitResponse( file2, outSpace.sharedMemoryId(), file1, inSpace.sharedMemoryId(), pid, size)); err = !in.readBoolean(); endpoints.add(ret); return ret; } catch (UnsatisfiedLinkError e) { throw IpcSharedMemoryUtils.linkError(e); } catch (IOException e) { if (log.isDebugEnabled()) log.debug( "Failed to process incoming connection " + "(was connection closed by another party):" + e.getMessage()); } catch (ClassNotFoundException e) { U.error(log, "Failed to process incoming connection.", e); } catch (ClassCastException e) { String msg = "Failed to process incoming connection (most probably, shared memory " + "rest endpoint has been configured by mistake)."; LT.warn(log, null, msg); sendErrorResponse(out, e); } catch (IpcOutOfSystemResourcesException e) { if (!omitOutOfResourcesWarn) LT.warn(log, null, OUT_OF_RESOURCES_MSG); sendErrorResponse(out, e); } catch (IgniteCheckedException e) { LT.error(log, e, "Failed to process incoming shared memory connection."); sendErrorResponse(out, e); } finally { // Exception has been thrown, need to free system resources. if (err) { if (inSpace != null) inSpace.forceClose(); // Safety. if (outSpace != null) outSpace.forceClose(); } } } catch (IOException e) { if (!Thread.currentThread().isInterrupted() && !accepted) throw new IgniteCheckedException("Failed to accept incoming connection.", e); if (!closed) LT.error( log, null, "Failed to process incoming shared memory connection: " + e.getMessage()); } finally { U.closeQuiet(sock); } } // while throw new IgniteInterruptedCheckedException("Socket accept was interrupted."); }