// Check if DatagramChannel.send while connected can include // address without throwing private static void test1() throws Exception { DatagramChannel sndChannel = DatagramChannel.open(); sndChannel.socket().bind(null); InetSocketAddress sender = new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort()); DatagramChannel rcvChannel = DatagramChannel.open(); rcvChannel.socket().bind(null); InetSocketAddress receiver = new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort()); rcvChannel.connect(sender); sndChannel.connect(receiver); ByteBuffer bb = ByteBuffer.allocate(256); bb.put("hello".getBytes()); bb.flip(); int sent = sndChannel.send(bb, receiver); bb.clear(); rcvChannel.receive(bb); bb.flip(); CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb); if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed"); rcvChannel.close(); sndChannel.close(); }
void isReadable(SelectionKey k) { EventableChannel ec = (EventableChannel) k.attachment(); long b = ec.getBinding(); if (ec.isWatchOnly()) { if (ec.isNotifyReadable()) eventCallback(b, EM_CONNECTION_NOTIFY_READABLE, null); } else { myReadBuffer.clear(); try { ec.readInboundData(myReadBuffer); myReadBuffer.flip(); if (myReadBuffer.limit() > 0) { if (ProxyConnections != null) { EventableChannel target = ProxyConnections.get(b); if (target != null) { ByteBuffer myWriteBuffer = ByteBuffer.allocate(myReadBuffer.limit()); myWriteBuffer.put(myReadBuffer); myWriteBuffer.flip(); target.scheduleOutboundData(myWriteBuffer); } else { eventCallback(b, EM_CONNECTION_READ, myReadBuffer); } } else { eventCallback(b, EM_CONNECTION_READ, myReadBuffer); } } } catch (IOException e) { UnboundConnections.add(b); } } }
public static void main(String args[]) { try { aServer asr = new aServer(); // file channel. FileInputStream is = new FileInputStream(""); is.read(); FileChannel cha = is.getChannel(); ByteBuffer bf = ByteBuffer.allocate(1024); bf.flip(); cha.read(bf); // Path Paths Path pth = Paths.get("", ""); // Files some static operation. Files.newByteChannel(pth); Files.copy(pth, pth); // file attribute, other different class for dos and posix system. BasicFileAttributes bas = Files.readAttributes(pth, BasicFileAttributes.class); bas.size(); } catch (Exception e) { System.err.println(e); } System.out.println("hello "); }
// Check if the datagramsocket adaptor can send with a packet // that has not been initialized with an address; the legacy // datagram socket will send in this case private static void test2() throws Exception { DatagramChannel sndChannel = DatagramChannel.open(); sndChannel.socket().bind(null); InetSocketAddress sender = new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort()); DatagramChannel rcvChannel = DatagramChannel.open(); rcvChannel.socket().bind(null); InetSocketAddress receiver = new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort()); rcvChannel.connect(sender); sndChannel.connect(receiver); byte b[] = "hello".getBytes("UTF-8"); DatagramPacket pkt = new DatagramPacket(b, b.length); sndChannel.socket().send(pkt); ByteBuffer bb = ByteBuffer.allocate(256); rcvChannel.receive(bb); bb.flip(); CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb); if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed"); // Check that the pkt got set with the target address; // This is legacy behavior if (!pkt.getSocketAddress().equals(receiver)) throw new RuntimeException("Test failed"); rcvChannel.close(); sndChannel.close(); }
private void recv(SocketChannel sc, ClientInfo ci) throws IOException { ci.channel.read(ci.inBuf); ByteBuffer tmpBuf = ci.inBuf.duplicate(); tmpBuf.flip(); int bytesProcessed = 0; boolean doneLoop = false; while (!doneLoop) { byte b; try { b = tmpBuf.get(); } catch (BufferUnderflowException bue) { // Processed all data in buffer ci.inBuf.clear(); doneLoop = true; break; } switch (b) { case TypeServerConstants.WELCOME: bytesProcessed++; break; case TypeServerConstants.GET_STRING_REQUEST: bytesProcessed++; if (ci.outputPending) { // Client is backed up. We can't append to // the byte buffer because it's in the wrong // state. We could allocate another buffer // here and change our send method to know // about multiple buffers, but we'll just // assume that the client is dead break; } ci.outBuf.put(TypeServerConstants.GET_STRING_RESPONSE); ByteBuffer strBuf = encoder.encode(testString); ci.outBuf.putShort((short) strBuf.remaining()); ci.outBuf.put(strBuf); ci.outBuf.flip(); send(sc, ci); break; case TypeServerConstants.GET_STRING_RESPONSE: int startPos = tmpBuf.position(); try { int nBytes = tmpBuf.getInt(); byte[] buf = new byte[nBytes]; tmpBuf.get(buf); bytesProcessed += buf.length + 5; String s = new String(buf); // Send the string to the GUI break; } catch (BufferUnderflowException bue) { // Processed all available data ci.inBuf.position(ci.inBuf.position() + bytesProcessed); doneLoop = true; } break; } } }
public static void main(String[] args) throws Exception { outBuf.put("Blah Blah".getBytes()); outBuf.flip(); test1(); // This test has been disabled because there are many circumstances // under which no ICMP port unreachable packets are received // See http://java.sun.com/j2se/1.4/networking-relnotes.html if ((args.length > 0) && (args[0].equals("test2"))) { outBuf.rewind(); test2(); } }
public static void main(String args[]) throws Exception { final int ENOUGH_SIZE = 1024; final int SMALL_SIZE = 4; boolean isBlocked = true; int size = ENOUGH_SIZE; if (args.length > 0) { int opt = Integer.parseInt(args[0]); switch (opt) { case 1: isBlocked = true; size = ENOUGH_SIZE; break; case 2: isBlocked = true; size = SMALL_SIZE; break; case 3: isBlocked = false; size = ENOUGH_SIZE; break; case 4: isBlocked = false; size = SMALL_SIZE; break; } } DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(isBlocked); ByteBuffer buffer = ByteBuffer.allocate(size); DatagramSocket socket = channel.socket(); SocketAddress localAddr = new InetSocketAddress(8000); socket.bind(localAddr); while (true) { System.out.println("开始接收数据报"); SocketAddress remoteAddr = channel.receive(buffer); if (remoteAddr == null) { System.out.println("没有接收到数据报"); } else { buffer.flip(); System.out.println("接收到的数据报的大小为" + buffer.remaining()); } Thread.sleep(500); } }
void isReadable(SelectionKey k) { EventableChannel ec = (EventableChannel) k.attachment(); long b = ec.getBinding(); if (ec.isWatchOnly()) { if (ec.isNotifyReadable()) eventCallback(b, EM_CONNECTION_NOTIFY_READABLE, null); } else { myReadBuffer.clear(); try { ec.readInboundData(myReadBuffer); myReadBuffer.flip(); if (myReadBuffer.limit() > 0) eventCallback(b, EM_CONNECTION_READ, myReadBuffer); } catch (IOException e) { UnboundConnections.add(b); } } }
public void resendMessage(Message message, IP remoteAddress, int remotePort) throws IOException { if (remoteAddress == null) remoteAddress = IP.getLocalHost(); message.setSentStamp(getConvertedTime(remoteAddress, remotePort)); message.setMessageServer(this); try { sendBuffer.clear(); sendBuffer.put(extractor.convertMessage(message)); sendBuffer.flip(); channel.send(sendBuffer, new InetSocketAddress(remoteAddress.toString(), remotePort)); message.setRemoteAddress(remoteAddress); message.setRemotePort(remotePort); messageSent(message); } catch (IllegalAccessException exc) { throw new RuntimeException(exc); } catch (IllegalArgumentException exc) { throw new RuntimeException(exc); } catch (InvocationTargetException exc) { throw new RuntimeException(exc); } }
private void dispatchMessage( TcpAddress incomingAddress, ByteBuffer byteBuffer, long bytesRead) { byteBuffer.flip(); if (logger.isDebugEnabled()) { logger.debug( "Received message from " + incomingAddress + " with length " + bytesRead + ": " + new OctetString(byteBuffer.array(), 0, (int) bytesRead).toHexString()); } ByteBuffer bis; if (isAsyncMsgProcessingSupported()) { byte[] bytes = new byte[(int) bytesRead]; System.arraycopy(byteBuffer.array(), 0, bytes, 0, (int) bytesRead); bis = ByteBuffer.wrap(bytes); } else { bis = ByteBuffer.wrap(byteBuffer.array(), 0, (int) bytesRead); } fireProcessMessage(incomingAddress, bis); }
/** * Decode file charset. * * @param f File to process. * @return File charset. * @throws IOException in case of error. */ public static Charset decode(File f) throws IOException { SortedMap<String, Charset> charsets = Charset.availableCharsets(); String[] firstCharsets = { Charset.defaultCharset().name(), "US-ASCII", "UTF-8", "UTF-16BE", "UTF-16LE" }; Collection<Charset> orderedCharsets = U.newLinkedHashSet(charsets.size()); for (String c : firstCharsets) if (charsets.containsKey(c)) orderedCharsets.add(charsets.get(c)); orderedCharsets.addAll(charsets.values()); try (RandomAccessFile raf = new RandomAccessFile(f, "r")) { FileChannel ch = raf.getChannel(); ByteBuffer buf = ByteBuffer.allocate(4096); ch.read(buf); buf.flip(); for (Charset charset : orderedCharsets) { CharsetDecoder decoder = charset.newDecoder(); decoder.reset(); try { decoder.decode(buf); return charset; } catch (CharacterCodingException ignored) { } } } return Charset.defaultCharset(); }
private synchronized DBMessage go(DBMessage msg, ByteDecoder decoder) throws IOException { if (_sock == null) _open(); { ByteBuffer out = msg.prepare(); while (out.remaining() > 0) _sock.write(out); } if (_pool != null) _pool._everWorked = true; if (decoder == null) return null; ByteBuffer response = decoder._buf; if (response.position() != 0) throw new IllegalArgumentException(); int read = 0; while (read < DBMessage.HEADER_LENGTH) read += _read(response); int len = response.getInt(0); if (len <= DBMessage.HEADER_LENGTH) throw new IllegalArgumentException("db sent invalid length: " + len); if (len > response.capacity()) throw new IllegalArgumentException( "db message size is too big (" + len + ") " + "max is (" + response.capacity() + ")"); response.limit(len); while (read < len) read += _read(response); if (read != len) throw new RuntimeException("something is wrong"); response.flip(); return new DBMessage(response); }
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" ); } }
public static void main(String[] args) { try { System.out.println("CliTest.java"); // create TCP socket channel SocketChannel channel = SocketChannel.open(); System.out.println("CliTest.java: channel created"); channel.connect(new InetSocketAddress("localhost", PORT)); System.out.println("CliTest.java: channel socket connected"); System.out.println(); // create & send a login message byte[] bytes = LoginMessage.getLoginMessage("user1", "password1"); System.out.println("CliTest.java: login message created"); System.out.println(LoginMessage.getMessageString(bytes)); System.out.printf("CliTest.java: login message length in bytes: %d\n", bytes.length); ByteBuffer buf = ByteBuffer.allocate(4096); buf.put(bytes); buf.flip(); // System.out.printf("CliTest.java: buf.remaining before channel.write(): %d\n", // buf.remaining()); int numwritten = channel.write(buf); System.out.printf( "CliTest.java: login mesage written: number of bytes written: %d\n", numwritten); // read reply message buf.clear(); int numread = channel.read(buf); bytes = new byte[numread]; buf.flip(); buf.get(bytes); if (LoginMessage.isLoginSuccessMessage(bytes)) { System.out.printf( "CliTest.java: first message read: Success Message: number of bytes read: %d\n", numread); // get remote port number from success message int port = LoginMessage.getPort(bytes); System.out.printf("Port Number: %d\n", port); byte playerid = LoginMessage.getPlayerId(bytes); System.out.printf("Player id: %d\n", playerid); String mcastString = LoginMessage.getMulticastAddress(bytes); System.out.printf("Multicast Address: %s\n", mcastString); // create datagram channel & connect to rem port DatagramChannel dchannel = DatagramChannel.open(); dchannel.socket().bind(new InetSocketAddress(0)); dchannel.socket().connect(new InetSocketAddress(channel.socket().getInetAddress(), port)); // get localport of datagram socket int localport = dchannel.socket().getLocalPort(); System.out.printf("UDP local port: %d\n", localport); // send success message to send port number to server bytes = LoginMessage.getLoginSuccessMessage(playerid, null, localport); buf.clear(); buf.put(bytes); buf.flip(); channel.write(buf); DeathMessage dm = new DeathMessage((byte) 1, (byte) 1); bytes = dm.getByteMessage(); buf.clear(); buf.put(bytes); buf.flip(); channel.write(buf); } else { System.out.printf( "CliTest.java: first message read: NOT Success Message: number of bytes read: %d\n", numread); } channel.close(); } catch (Exception e) { e.printStackTrace(); } }
private void readMessage(SelectionKey sk, SocketChannel readChannel, TcpAddress incomingAddress) throws IOException { // note that socket has been used SocketEntry entry = (SocketEntry) sockets.get(incomingAddress); if (entry != null) { entry.used(); ByteBuffer readBuffer = entry.getReadBuffer(); if (readBuffer != null) { readChannel.read(readBuffer); if (readBuffer.hasRemaining()) { readChannel.register(selector, SelectionKey.OP_READ, entry); } else { dispatchMessage(incomingAddress, readBuffer, readBuffer.capacity()); } return; } } ByteBuffer byteBuffer = ByteBuffer.wrap(buf); byteBuffer.limit(messageLengthDecoder.getMinHeaderLength()); long bytesRead = readChannel.read(byteBuffer); if (logger.isDebugEnabled()) { logger.debug("Reading header " + bytesRead + " bytes from " + incomingAddress); } MessageLength messageLength = new MessageLength(0, Integer.MIN_VALUE); if (bytesRead == messageLengthDecoder.getMinHeaderLength()) { messageLength = messageLengthDecoder.getMessageLength(ByteBuffer.wrap(buf)); if (logger.isDebugEnabled()) { logger.debug("Message length is " + messageLength); } if ((messageLength.getMessageLength() > getMaxInboundMessageSize()) || (messageLength.getMessageLength() <= 0)) { logger.error( "Received message length " + messageLength + " is greater than inboundBufferSize " + getMaxInboundMessageSize()); synchronized (entry) { entry.getSocket().close(); logger.info("Socket to " + entry.getPeerAddress() + " closed due to an error"); } } else { byteBuffer.limit(messageLength.getMessageLength()); bytesRead += readChannel.read(byteBuffer); if (bytesRead == messageLength.getMessageLength()) { dispatchMessage(incomingAddress, byteBuffer, bytesRead); } else { byte[] message = new byte[byteBuffer.limit()]; byteBuffer.flip(); byteBuffer.get(message, 0, byteBuffer.limit() - byteBuffer.remaining()); entry.setReadBuffer(ByteBuffer.wrap(message)); } readChannel.register(selector, SelectionKey.OP_READ, entry); } } else if (bytesRead < 0) { logger.debug("Socket closed remotely"); sk.cancel(); readChannel.close(); TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_DISCONNECTED_REMOTELY, null); fireConnectionStateChanged(e); } }