static void insertString(String str, ByteBuffer buf) throws java.io.UnsupportedEncodingException { if (str != null && str.length() > 0) { buf.putInt(str.length() + 1); buf.put(str.getBytes("UTF-8"), 0, str.length()); buf.put((byte) 0); } else { // buffer is null or length 0 buf.putInt(0); } }
static void insertByteString(byte[] array, ByteBuffer buf) throws java.io.UnsupportedEncodingException { if (array != null && array.length > 0) { buf.putInt(array.length); buf.put(array, 0, array.length); buf.put((byte) 0); } else { // buffer is null or length 0 buf.putInt(0); } }
// 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 byte[] getNBOHost(String h) { if (h.equals(PEER)) return null; byte hostBytes[] = h.getBytes(); int len = Array.getLength(hostBytes); ByteBuffer buf = ByteBuffer.allocate(len); buf.put(hostBytes); buf.order(ByteOrder.BIG_ENDIAN); buf.rewind(); return (buf.array()); }
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(); } }
// creates the header and pads the content returning a new byte[] // in the proper format. The secret is 4bytes (int), the step // is 2 bytes (short). public static byte[] createBuffer(byte[] content, int secret, short step) { short studentNum = 456; // my student number is 1340456 int paddedSize = content.length; while (paddedSize % 4 != 0) { paddedSize++; } ByteBuffer bb = ByteBuffer.allocate(HEADER_SIZE + paddedSize); bb.putInt(content.length); bb.putInt(secret); bb.putShort(step); bb.putShort(studentNum); bb.put(content); return bb.array(); }
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); } }
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(); } }
/** * Opens new WebRTC data channel using specified parameters. * * @param type channel type as defined in control protocol description. Use 0 for "reliable". * @param prio channel priority. The higher the number, the lower the priority. * @param reliab Reliability Parameter<br> * This field is ignored if a reliable channel is used. If a partial reliable channel with * limited number of retransmissions is used, this field specifies the number of * retransmissions. If a partial reliable channel with limited lifetime is used, this field * specifies the maximum lifetime in milliseconds. The following table summarizes this:<br> * </br> * <p>+------------------------------------------------+------------------+ | Channel Type | * Reliability | | | Parameter | * +------------------------------------------------+------------------+ | * DATA_CHANNEL_RELIABLE | Ignored | | DATA_CHANNEL_RELIABLE_UNORDERED | Ignored | | * DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT | Number of RTX | | * DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED | Number of RTX | | * DATA_CHANNEL_PARTIAL_RELIABLE_TIMED | Lifetime in ms | | * DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED | Lifetime in ms | * +------------------------------------------------+------------------+ * @param sid SCTP stream id that will be used by new channel (it must not be already used). * @param label text label for the channel. * @return new instance of <tt>WebRtcDataStream</tt> that represents opened WebRTC data channel. * @throws IOException if IO error occurs. */ public synchronized WebRtcDataStream openChannel( int type, int prio, long reliab, int sid, String label) throws IOException { if (channels.containsKey(sid)) { throw new IOException("Channel on sid: " + sid + " already exists"); } // Label Length & Label byte[] labelBytes; int labelByteLength; if (label == null) { labelBytes = null; labelByteLength = 0; } else { labelBytes = label.getBytes("UTF-8"); labelByteLength = labelBytes.length; if (labelByteLength > 0xFFFF) labelByteLength = 0xFFFF; } // Protocol Length & Protocol String protocol = WEBRTC_DATA_CHANNEL_PROTOCOL; byte[] protocolBytes; int protocolByteLength; if (protocol == null) { protocolBytes = null; protocolByteLength = 0; } else { protocolBytes = protocol.getBytes("UTF-8"); protocolByteLength = protocolBytes.length; if (protocolByteLength > 0xFFFF) protocolByteLength = 0xFFFF; } ByteBuffer packet = ByteBuffer.allocate(12 + labelByteLength + protocolByteLength); // Message open new channel on current sid // Message Type packet.put((byte) MSG_OPEN_CHANNEL); // Channel Type packet.put((byte) type); // Priority packet.putShort((short) prio); // Reliability Parameter packet.putInt((int) reliab); // Label Length packet.putShort((short) labelByteLength); // Protocol Length packet.putShort((short) protocolByteLength); // Label if (labelByteLength != 0) { packet.put(labelBytes, 0, labelByteLength); } // Protocol if (protocolByteLength != 0) { packet.put(protocolBytes, 0, protocolByteLength); } int sentCount = sctpSocket.send(packet.array(), true, sid, WEB_RTC_PPID_CTRL); if (sentCount != packet.capacity()) { throw new IOException("Failed to open new chanel on sid: " + sid); } WebRtcDataStream channel = new WebRtcDataStream(sctpSocket, sid, label, false); channels.put(sid, channel); return channel; }
static void insertByteArray(byte[] array, ByteBuffer buf) { if (array != null && array.length > 0) { buf.putInt(array.length); buf.put(array, 0, array.length); } else buf.putInt(0); }