* @param connectTimeout in milliseconds
* @throws JSchException if any errors occur
*/
public void connect(int connectTimeout) throws JSchException {
if( isConnected() ) {
throw new JSchException("Channel is already connected");
} else if( !_session.isConnected() ) {
throw new JSchException("Session is not connected");
}
_connectTimeout = connectTimeout; // Set connection timeout
try {
Buffer buffer = new Buffer(100);
Packet packet = new Packet(buffer);
// send
// byte SSH_MSG_CHANNEL_OPEN(90)
// string channel type //
// uint32 sender channel // 0
// uint32 initial window size // 0x100000(65536)
// uint32 maxmum packet size // 0x4000(16384)
packet.reset();
buffer.putByte(SSH_MSG_CHANNEL_OPEN);
buffer.putString(_type);
buffer.putInt(_id);
buffer.putInt(_localWindowSize);
buffer.putInt(_localMaxPacketSize);
_session.write(packet);
int retry = 1000; // Note: Max timeout is 50 seconds (1000 retries * 50ms sleep)
long start = System.currentTimeMillis();
while( _recipient == -1 && _session.isConnected() && retry-- > 0 ) {
if( _connectTimeout > 0L && (System.currentTimeMillis() - start) > _connectTimeout ) {
throw new JSchException("Failed to open channel: connection timeout after " + _connectTimeout + " ms");
}
try { Thread.sleep(50); } catch(Exception ee) { /* Ignore error. */ }
}
if( !_session.isConnected() ) {
throw new JSchException("Failed to open channel: session is not connected");
} else if( retry == 0 ) {
throw new JSchException("Failed to open channel: no response");
}
/*
* At the failure in opening the channel on the sshd,
* 'SSH_MSG_CHANNEL_OPEN_FAILURE' will be sent from sshd and it will
* be processed in Session#run().
*/
if( isClosed() ) {
throw new JSchException("Failed to open channel: "+_exitstatus);
}
_connected = true;
start();
} catch(JSchException je) {
_connected = false;
disconnect();
throw je;
} catch(Exception e) {
_connected = false;
disconnect();
throw new JSchException("Failed to open channel "+getClass().getSimpleName()+": "+_exitstatus, e);
}
}