List of usage examples for java.nio.channels SocketChannel socket
public abstract Socket socket();
From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java
@Test public void testSufficientThreads() throws Exception { final ExecutorService exec = Executors.newFixedThreadPool(3); final CountDownLatch messageLatch = new CountDownLatch(1); Future<Object> future = exec.submit(() -> { SocketChannel channel = mock(SocketChannel.class); Socket socket = mock(Socket.class); Mockito.when(channel.socket()).thenReturn(socket); doAnswer(invocation -> {// ww w . ja v a2 s . c o m ByteBuffer buffer = invocation.getArgument(0); buffer.position(1025); buffer.put((byte) '\r'); buffer.put((byte) '\n'); return 1027; }).when(channel).read(Mockito.any(ByteBuffer.class)); final TcpNioConnection connection = new TcpNioConnection(channel, false, false, null, null); connection.setTaskExecutor(exec); connection.registerListener(message -> { messageLatch.countDown(); return false; }); connection.setMapper(new TcpMessageMapper()); connection.setDeserializer(new ByteArrayCrLfSerializer()); Method method = TcpNioConnection.class.getDeclaredMethod("doRead"); method.setAccessible(true); try { for (int i = 0; i < 20; i++) { method.invoke(connection); } } catch (Exception e) { e.printStackTrace(); throw (Exception) e.getCause(); } return null; }); future.get(60, TimeUnit.SECONDS); assertTrue(messageLatch.await(10, TimeUnit.SECONDS)); }
From source file:org.cloudata.core.commitlog.FileTransferThread.java
public void run() { SocketChannel socketChannel = null; try {//from w w w. j a v a 2 s . co m if (selector.select(5000) > 0) { Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); if (key.isValid() && key.isAcceptable()) { socketChannel = ssc.accept(); transfer(channelList, socketChannel); } iter.remove(); } } else { LOG.warn("No responses from client asking to transfter file for 5 sec"); } } catch (IOException e) { LOG.warn("transfering file is fail", e); } finally { if (socketChannel != null) { try { socketChannel.socket().close(); socketChannel.close(); } catch (IOException e) { /* ignored */ } } } LOG.debug("File transfer thread is done"); }
From source file:morphy.service.SocketConnectionService.java
private synchronized void onNewInput(SocketChannel channel) { if (!channel.isOpen()) return;/*w w w. j av a2s. co m*/ try { if (channel.isConnected()) { SocketChannelUserSession session = socketToSession.get(channel.socket()); if (session == null) { if (LOG.isErrorEnabled()) { LOG.error("Received a read on a socket not being managed. This is likely a bug."); } disposeSocketChannel(channel); } else { synchronized (session.getInputBuffer()) { String message = readMessage(channel); if (message != null && message.equals(MSG_TIMESEAL_OK)) { // Don't need to do anything. This was just the timeseal init string. } else if (message == null && channel.isOpen()) { session.disconnect(); } else if (message == null) { session.disconnect(); } else if (message.length() > 0) { /*if (!socketInputForCmd.containsKey(channel.socket())) { socketInputForCmd.put(channel.socket(), new StringBuilder()); } int c = (int)message.charAt(0); if (c != 10 && c != 13) { socketInputForCmd.get(channel.socket()).append(message); //LOG.info(c); } else { message = socketInputForCmd.get(channel.socket()).toString(); socketInputForCmd.put(channel.socket(), new StringBuilder()); LOG.info("Read: " + session.getUser().getUserName() + " \"" + message + "\""); } LOG.info(c + " " + socketInputForCmd.get(channel.socket()));*/ boolean expandAliases = true; if (message.startsWith("$$")) { message = message.substring(2); expandAliases = false; } else { session.touchLastReceivedTime(); session.getUser().getUserVars().getVariables().put("busy", ""); expandAliases = true; } session.getInputBuffer().append(message); if (session.getInputBuffer().indexOf("\n") != -1) { LOG.info("Read: " + session.getUser().getUserName() + " \"" + message + "\""); } int carrageReturnIndex = -1; while ((carrageReturnIndex = session.getInputBuffer().indexOf("\n")) != -1) { String command = session.getInputBuffer().substring(0, carrageReturnIndex).trim(); session.getInputBuffer().delete(0, carrageReturnIndex + 1); if (session .getCurrentState() == SocketChannelUserSession.UserSessionState.LOGIN_NEED_PASSWORD) { handlePasswordPromptText(session, command); } else if (command.equals("") || command.equals("\n") || command.equals("\n\r")) { session.send(""); } else if (session .getCurrentState() == SocketChannelUserSession.UserSessionState.LOGIN_NEED_USERNAME) { handleLoginPromptText(session, command); } else { if (expandAliases) { CommandService.getInstance().processCommandAndCheckAliases(command, session); } else { CommandService.getInstance().processCommand(command, session); } } } } } } } } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error("Error reading socket channel or processing command ", t); } } }
From source file:morphy.user.SocketChannelUserSession.java
public SocketChannelUserSession(User user, SocketChannel channel) { this.user = user; this.channel = channel; inputBuffer = new StringBuilder(400); loginTime = System.currentTimeMillis(); objectMap = new TreeMap<UserSessionKey, Object>(); if (!UserService.getInstance().isAdmin(user.getUserName())) idleLogoutTimer = new Timer(); gamesObserving = new ArrayList<Integer>(); if (LOG.isInfoEnabled()) { LOG.info("Created SocketChannelUserSession user " + user.getUserName() + " " + channel.socket().getInetAddress()); }//from w ww . j a v a 2s . c om multipleLogins = new ArrayList<SocketChannelUserSession>(0); }
From source file:com.bittorrent.mpetazzoni.client.ConnectionHandler.java
/** * Accept the next incoming connection./*from w ww . java 2 s. c o m*/ * * <p> * When a new peer connects to this service, wait for it to send its * handshake. We then parse and check that the handshake advertises the * torrent hash we expect, then reply with our own handshake. * </p> * * <p> * If everything goes according to plan, notify the * <code>IncomingConnectionListener</code>s with the connected socket and * the parsed peer ID. * </p> * * @param client The accepted client's socket channel. */ private void accept(SocketChannel client) throws IOException, SocketTimeoutException { try { logger.debug("New incoming connection, waiting for handshake..."); Handshake hs = this.validateHandshake(client, null); int sent = this.sendHandshake(client); logger.trace("Replied to {} with handshake ({} bytes).", this.socketRepr(client), sent); // Go to non-blocking mode for peer interaction client.configureBlocking(false); client.socket().setSoTimeout(CLIENT_KEEP_ALIVE_MINUTES * 60 * 1000); this.fireNewPeerConnection(client, hs.getPeerId()); } catch (ParseException pe) { logger.info("Invalid handshake from {}: {}", this.socketRepr(client), pe.getMessage()); IOUtils.closeQuietly(client); } catch (IOException ioe) { logger.warn("An error occured while reading an incoming " + "handshake: {}", ioe.getMessage()); if (client.isConnected()) { IOUtils.closeQuietly(client); } } }
From source file:oz.hadoop.yarn.api.net.ApplicationContainerServerImpl.java
/** * // w w w .j ava 2s.co m */ @Override void doAccept(SelectionKey selectionKey) throws IOException { ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel(); SocketChannel channel = serverChannel.accept(); if (this.expectedClientContainersMonitor.getCount() == 0) { logger.warn("Refusing connection from " + channel.getRemoteAddress() + ", since " + this.expectedClientContainers + " ApplicationContainerClients " + "identified by 'expectedClientContainers' already connected."); this.closeChannel(channel); } else { channel.configureBlocking(false); SelectionKey clientSelectionKey = channel.register(this.selector, SelectionKey.OP_READ); if (logger.isInfoEnabled()) { logger.info("Accepted conection request from: " + channel.socket().getRemoteSocketAddress()); } if (this.masterSelectionKey != null) { this.containerDelegates.put(clientSelectionKey, new ContainerDelegateImpl(clientSelectionKey, this)); } else { this.masterSelectionKey = clientSelectionKey; this.masterSelectionKey.attach(true); } this.expectedClientContainersMonitor.countDown(); } }
From source file:org.reunionemu.jreunion.server.World.java
@Override public void handleEvent(Event event) { if (event instanceof ServerEvent) { if (event instanceof ServerStartEvent) { start();/*from ww w . j a v a 2 s. c o m*/ } if (event instanceof ServerStopEvent) { stop(); } } if (event instanceof NetworkEvent) { SocketChannel socketChannel = ((NetworkEvent) event).getSocketChannel(); if (event instanceof NetworkAcceptEvent) { NetworkAcceptEvent networkAcceptEvent = (NetworkAcceptEvent) event; Network network = (Network) networkAcceptEvent.getSource(); Client client = new Client(this, socketChannel); client.addEventListener(NetworkSendEvent.class, network); network.addEventListener(NetworkDataEvent.class, client, new NetworkEvent.NetworkFilter(socketChannel)); LoggerFactory.getLogger(World.class) .info("Got connection from {local=" + socketChannel.socket().getLocalSocketAddress() + " remote=" + socketChannel.socket().getRemoteSocketAddress() + "}\n"); client.setState(Client.State.ACCEPTED); clients.put(socketChannel, client); fireEvent(ClientConnectEvent.class, client); } if (event instanceof NetworkDisconnectEvent) { Client client = clients.remove(socketChannel); } } }
From source file:com.springrts.springls.ServerThread.java
/** Check for new client connections */ private void acceptNewConnections() { try {//from www . j av a 2s . c om SocketChannel clientChannel; // since sSockChan is non-blocking, this will return immediately // regardless of whether there is a connection available while ((clientChannel = sSockChan.accept()) != null) { if (getContext().getServer().isRedirectActive()) { LOG.debug("Client redirected to {}: {}", getContext().getServer().getRedirectAddress().getHostAddress(), clientChannel.socket().getInetAddress().getHostAddress()); redirectAndKill(clientChannel.socket()); continue; } Client client = getContext().getClients().addNewClient(clientChannel, readSelector, SEND_BUFFER_SIZE); if (client == null) { continue; } // from this point on, we know that client // has been successfully connected client.sendWelcomeMessage(); LOG.debug("New client connected: {}", client.getIp().getHostAddress()); } } catch (Exception ex) { LOG.error("Exception in acceptNewConnections(): " + ex.getMessage(), ex); } }
From source file:morphy.service.SocketConnectionService.java
private synchronized void onNewChannel(SocketChannel channel) { if (LOG.isInfoEnabled()) { LOG.info("onNewChannel();"); }//from w w w . j ava 2s . c o m try { SocketChannelUserSession session = new SocketChannelUserSession(new User(), channel); session.setCurrentState(SocketChannelUserSession.UserSessionState.LOGIN_NEED_USERNAME); socketToSession.put(channel.socket(), session); // ByteBuffer buffer = BufferUtils.createBuffer(ScreenService // .getInstance().getScreen(Screen.Login)); // channel.write(buffer); sendWithoutPrompt(ScreenService.getInstance().getScreen(Screen.Login), session); if (LOG.isInfoEnabled()) { LOG.info("Received socket connection " + channel.socket().getInetAddress()); } } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error("Error writing to SocketChannel " + channel.socket().getInetAddress(), t); } disposeSocketChannel(channel); } }
From source file:com.turn.ttorrent.client.Client.java
/** * Handle a new peer connection./*from ww w. j a v a 2s . co m*/ * * <p> * This handler is called once the connection has been successfully * established and the handshake exchange made. This generally simply means * binding the peer to the socket, which will put in place the communication * thread and logic with this peer. * </p> * * @param channel The connected socket channel to the remote peer. Note * that if the peer somehow rejected our handshake reply, this socket might * very soon get closed, but this is handled down the road. * @param peerId The byte-encoded peerId extracted from the peer's * handshake, after validation. * @see com.turn.ttorrent.client.peer.SharingPeer */ @Override public void handleNewPeerConnection(SocketChannel channel, byte[] peerId) { Peer search = new Peer(channel.socket().getInetAddress().getHostAddress(), channel.socket().getPort(), (peerId != null ? ByteBuffer.wrap(peerId) : (ByteBuffer) null)); logger.info("Handling new peer connection with {}...", search); SharingPeer peer = this.getOrCreatePeer(search); try { synchronized (peer) { if (peer.isConnected()) { logger.info("Already connected with {}, closing link.", peer); channel.close(); return; } peer.register(this); peer.bind(channel); } this.connected.put(peer.getHexPeerId(), peer); peer.register(this.torrent); logger.debug("New peer connection with {} [{}/{}].", new Object[] { peer, this.connected.size(), this.peers.size() }); } catch (Exception e) { this.connected.remove(peer.getHexPeerId()); logger.warn("Could not handle new peer connection " + "with {}: {}", peer, e.getMessage()); } }