public IRubyObject initialize(IRubyObject[] args) {
Arity.checkArgumentCount(getRuntime(), args, 2, 4);
String remoteHost = args[0].isNil()? "localhost" : args[0].convertToString().toString();
int remotePort = getPortFrom(args[1]);
String localHost = args.length >= 3 ? args[2].convertToString().toString() : null;
int localPort = args.length == 4 ? getPortFrom(args[3]) : 0;
try {
SocketChannel channel = null;
if(localHost == null) {
InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(remoteHost), remotePort);
channel = SocketChannel.open(addr);
} else {
channel = SocketChannel.open();
Socket socket = channel.socket();
socket.bind(new InetSocketAddress(InetAddress.getByName(localHost), localPort));
socket.connect(new InetSocketAddress(InetAddress.getByName(remoteHost), remotePort));
}
channel.finishConnect();
initSocket(new ChannelDescriptor(channel, RubyIO.getNewFileno(), new ModeFlags(ModeFlags.RDWR), new FileDescriptor()));
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
} catch(ConnectException e) {
throw getRuntime().newErrnoECONNREFUSEDError();
} catch(UnknownHostException e) {
throw sockerr(this, "initialize: name or service not known");
} catch(IOException e) {
throw sockerr(this, "initialize: name or service not known");
}
return this;
}
|