@JRubyMethod(required = 1, rest = true)
public IRubyObject send(ThreadContext context, IRubyObject[] args) {
try {
int written;
if (args.length >= 3) { // host and port given
RubyString nameStr = args[2].convertToString();
RubyString data = args[0].convertToString();
ByteBuffer buf = ByteBuffer.wrap(data.getBytes());
byte [] buf2 = data.getBytes();
DatagramPacket sendDP = null;
int port;
if (args[3] instanceof RubyString) {
jnr.netdb.Service service = jnr.netdb.Service.getServiceByName(args[3].asJavaString(), "udp");
if (service != null) {
port = service.getPort();
} else {
port = (int)args[3].convertToInteger("to_i").getLongValue();
}
} else {
port = (int)args[3].convertToInteger().getLongValue();
}
InetAddress address = RubySocket.getRubyInetAddress(nameStr.getByteList());
InetSocketAddress addr =
new InetSocketAddress(address, port);
if (this.multicastStateManager == null) {
written = ((DatagramChannel) this.getChannel()).send(buf, addr);
}
else {
sendDP = new DatagramPacket(buf2, buf2.length, address, port);
MulticastSocket ms = this.multicastStateManager.getMulticastSocket();
ms.send(sendDP);
written = sendDP.getLength();
}
} else {
RubyString data = args[0].convertToString();
ByteBuffer buf = ByteBuffer.wrap(data.getBytes());
written = ((DatagramChannel) this.getChannel()).write(buf);
}
return context.getRuntime().newFixnum(written);
} catch (UnknownHostException e) {
throw sockerr(context.getRuntime(), "send: name or service not known");