本文整理了Java中java.nio.channels.SocketChannel.connect()
方法的一些代码示例,展示了SocketChannel.connect()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。SocketChannel.connect()
方法的具体详情如下:
包路径:java.nio.channels.SocketChannel
类名称:SocketChannel
方法名:connect
[英]Connects this channel's socket with a remote address.
If this channel is blocking, this method will suspend until connecting is finished or an I/O exception occurs. If the channel is non-blocking, this method will return true if the connection is finished at once or return false when the connection must be finished later by calling finishConnect().
This method can be called at any moment and can block other read and write operations while connecting. It executes the same security checks as the connect method of the Socket class.
[中]将此通道的套接字与远程地址连接。
如果此通道被阻塞,此方法将挂起,直到连接完成或发生I/O异常。如果通道是非阻塞的,则如果连接立即完成,则此方法将返回true;如果连接必须稍后通过调用finishConnect()完成,则此方法将返回false。
此方法可以随时调用,并且可以在连接时阻止其他读写操作。它执行与套接字类的connect方法相同的安全检查。
代码示例来源:origin: alibaba/cobar
public void connect(Selector selector) throws IOException {
channel.register(selector, SelectionKey.OP_CONNECT, this);
channel.connect(new InetSocketAddress(host, port));
}
代码示例来源:origin: apache/activemq
@Override
public Socket createSocket(InetAddress address, int port) throws IOException {
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress(address, port));
return channel.socket();
}
代码示例来源:origin: apache/nifi
private SocketChannel doConnect(InetSocketAddress addressToConnect) throws IOException {
SocketChannel channel = SocketChannel.open();
if (channel.connect(addressToConnect)) {
channel.configureBlocking(false);
channel.register(this.selector, SelectionKey.OP_READ);
} else {
throw new IllegalStateException("Failed to connect to Server at: " + addressToConnect);
}
return channel;
}
代码示例来源:origin: apache/activemq
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress(host, port));
return channel.socket();
}
代码示例来源:origin: wildfly/wildfly
public static boolean connect(SocketChannel ch, SocketAddress dest) throws IOException {
if(dest instanceof InetSocketAddress) {
InetAddress addr=((InetSocketAddress)dest).getAddress();
if(addr instanceof Inet6Address) {
Inet6Address tmp=(Inet6Address)addr;
if(tmp.getScopeId() != 0) {
dest=new InetSocketAddress(InetAddress.getByAddress(tmp.getAddress()),((InetSocketAddress)dest).getPort());
}
}
}
return ch.connect(dest);
}
代码示例来源:origin: robovm/robovm
/**
* Creates a socket channel and connects it to a socket address.
* <p>
* This method performs a call to {@code open()} followed by a call to
* {@code connect(SocketAddress)}.
*
* @param address
* the socket address to be connected to.
* @return the new connected channel.
* @throws AsynchronousCloseException
* if this channel is closed by another thread while this method
* is executing.
* @throws ClosedByInterruptException
* if another thread interrupts the calling thread while this
* operation is executing. The calling thread will have the
* interrupt state set and the channel will be closed.
* @throws UnresolvedAddressException
* if the address is not resolved.
* @throws UnsupportedAddressTypeException
* if the address type is not supported.
* @throws IOException
* if an I/O error occurs.
*/
public static SocketChannel open(SocketAddress address) throws IOException {
SocketChannel socketChannel = open();
if (socketChannel != null) {
socketChannel.connect(address);
}
return socketChannel;
}
代码示例来源:origin: apache/activemq
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddresss, int localPort) throws IOException {
SocketChannel channel = SocketChannel.open();
channel.socket().bind(new InetSocketAddress(localAddresss, localPort));
channel.connect(new InetSocketAddress(address, port));
return channel.socket();
}
};
代码示例来源:origin: i2p/i2p.i2p
if (port <= 0 || ip == null)
throw new IOException("Invalid NTCP address: " + naddr);
InetSocketAddress saddr = new InetSocketAddress(InetAddress.getByAddress(ip), port);
boolean connected = con.getChannel().connect(saddr);
if (connected) {
代码示例来源:origin: h2oai/h2o-2
public SocketChannel getTCPSocket() throws IOException {
// Under lock, claim an existing open socket if possible
synchronized(this) {
// Limit myself to the number of open sockets from node-to-node
while( _socksAvail == 0 )
try { wait(); } catch( InterruptedException ie ) { }
// Claim an open socket
SocketChannel sock = _socks[--_socksAvail];
if( sock != null ) {
if( sock.isOpen() ) return sock; // Return existing socket!
// Else its an already-closed socket, lower open TCP count
assert TCPS.get() > 0;
TCPS.decrementAndGet();
}
}
// Must make a fresh socket
SocketChannel sock2 = SocketChannel.open();
sock2.socket().setReuseAddress(true);
sock2.socket().setSendBufferSize(AutoBuffer.BBSIZE);
boolean res = sock2.connect( _key );
assert res && !sock2.isConnectionPending() && sock2.isBlocking() && sock2.isConnected() && sock2.isOpen();
TCPS.incrementAndGet(); // Cluster-wide counting
return sock2;
}
public synchronized void freeTCPSocket( SocketChannel sock ) {
代码示例来源:origin: apache/activemq
@Override
public Socket createSocket(String address, int port, InetAddress localAddresss, int localPort) throws IOException, UnknownHostException {
SocketChannel channel = SocketChannel.open();
channel.socket().bind(new InetSocketAddress(localAddresss, localPort));
channel.connect(new InetSocketAddress(address, port));
return channel.socket();
}
代码示例来源:origin: wuyinxian124/nettybook2
private void doConnect() throws IOException {
// 如果直接连接成功,则注册到多路复用器上,发送请求消息,读应答
if (socketChannel.connect(new InetSocketAddress(host, port))) {
socketChannel.register(selector, SelectionKey.OP_READ);
doWrite(socketChannel);
} else
socketChannel.register(selector, SelectionKey.OP_CONNECT);
}
代码示例来源:origin: apache/ignite
/**
* @param addr Node address.
* @param rmtNodeId Id of node to open connection check session with.
*/
public void init(InetSocketAddress addr, UUID rmtNodeId) {
boolean connect;
try {
ch = SocketChannel.open();
ch.configureBlocking(false);
ch.socket().setTcpNoDelay(true);
ch.socket().setKeepAlive(false);
connect = ch.connect(addr);
}
catch (Exception e) {
finish(false);
return;
}
if (!connect) {
sesMeta = new GridLeanMap<>(3);
// Set dummy key to identify connection-check outgoing connection.
sesMeta.put(TcpCommunicationSpi.CONN_IDX_META, new ConnectionKey(rmtNodeId, -1, -1, true));
sesMeta.put(SES_FUT_META, this);
nioSrvr.createSession(ch, sesMeta, true, new IgniteInClosure<IgniteInternalFuture<GridNioSession>>() {
@Override public void apply(IgniteInternalFuture<GridNioSession> fut) {
if (fut.error() != null)
finish(false);
}
});
}
}
代码示例来源:origin: stackoverflow.com
/*
* Reader
*/
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class Receiver {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
System.out.println("Receiver Start");
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(true);
if (sChannel.connect(new InetSocketAddress("localhost", 12345))) {
ObjectInputStream ois =
new ObjectInputStream(sChannel.socket().getInputStream());
String s = (String)ois.readObject();
System.out.println("String is: '" + s + "'");
}
System.out.println("End Receiver");
}
}
代码示例来源:origin: buptdavid/datastructure
private void doConnect() throws IOException{
// 如果直接连接成功,则注册到多路复用器上,发送请求消息,读应答
if(socketChannel.connect(new InetSocketAddress(host, port))){
socketChannel.register(selector, SelectionKey.OP_READ);
doWrite(socketChannel);
}else{
socketChannel.register(selector, SelectionKey.OP_CONNECT);
}
}
代码示例来源:origin: lealone/Lealone
@Override
protected void createConnectionInternal(NetEndpoint endpoint, AsyncConnectionManager connectionManager,
CountDownLatch latch) throws Exception {
InetSocketAddress inetSocketAddress = endpoint.getInetSocketAddress();
int socketRecvBuffer = 16 * 1024;
int socketSendBuffer = 8 * 1024;
SocketChannel channel = null;
try {
channel = SocketChannel.open();
channel.configureBlocking(false);
Socket socket = channel.socket();
socket.setReceiveBufferSize(socketRecvBuffer);
socket.setSendBufferSize(socketSendBuffer);
socket.setTcpNoDelay(true);
socket.setKeepAlive(true);
Attachment attachment = new Attachment();
attachment.connectionManager = connectionManager;
attachment.inetSocketAddress = inetSocketAddress;
attachment.latch = latch;
register(channel, SelectionKey.OP_CONNECT, attachment);
channel.connect(inetSocketAddress);
} catch (Exception e) {
closeChannel(channel);
throw e;
}
}
代码示例来源:origin: mpetazzoni/ttorrent
private void connectToPeersFromQueue() {
ConnectTask connectTask;
while ((connectTask = myConnectQueue.poll()) != null) {
if (stop || Thread.currentThread().isInterrupted()) {
return;
}
logger.debug("try connect to peer. Connect task is {}", connectTask);
try {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_CONNECT, connectTask);
socketChannel.connect(new InetSocketAddress(connectTask.getHost(), connectTask.getPort()));
} catch (IOException e) {
LoggerUtils.warnAndDebugDetails(logger, "unable connect. Connect task is {}", connectTask, e);
}
}
}
代码示例来源:origin: apache/activemq-artemis
public static boolean connect(SocketChannel ch, SocketAddress dest) throws IOException {
if(dest instanceof InetSocketAddress) {
InetAddress addr=((InetSocketAddress)dest).getAddress();
if(addr instanceof Inet6Address) {
Inet6Address tmp=(Inet6Address)addr;
if(tmp.getScopeId() != 0) {
dest=new InetSocketAddress(InetAddress.getByAddress(tmp.getAddress()),((InetSocketAddress)dest).getPort());
}
}
}
return ch.connect(dest);
}
代码示例来源:origin: wildfly/wildfly
final SocketChannel channel = SocketChannel.open();
boolean ok = false;
try {
ChannelListeners.invokeChannelListener(connection, bindListener);
if (channel.connect(destinationAddress)) {
selectorLog.tracef("Synchronous connect");
execute(ChannelListeners.getChannelListenerTask(connection, openListener));
代码示例来源:origin: wildfly/wildfly
public void run() {
try {
ch=SocketChannel.open();
ch.configureBlocking(true); // we want blocking behavior
ch.connect(new InetSocketAddress(host, 7500));
latch.await();
}
catch(Exception e) {
e.printStackTrace();
}
for(;;) {
total_bytes_sent.add(NioServerPerfTest.SIZE);
if(total_bytes_sent.sum() > NioServerPerfTest.BYTES_TO_SEND)
break;
buf.rewind();
try {
ch.write(buf);
total_msgs.increment();
}
catch(IOException e) {
e.printStackTrace();
}
}
Util.close(ch);
}
}
代码示例来源:origin: apache/activemq-artemis
public static boolean connect(SocketChannel ch, SocketAddress dest) throws IOException {
if(dest instanceof InetSocketAddress) {
InetAddress addr=((InetSocketAddress)dest).getAddress();
if(addr instanceof Inet6Address) {
Inet6Address tmp=(Inet6Address)addr;
if(tmp.getScopeId() != 0) {
dest=new InetSocketAddress(InetAddress.getByAddress(tmp.getAddress()),((InetSocketAddress)dest).getPort());
}
}
}
return ch.connect(dest);
}
内容来源于网络,如有侵权,请联系作者删除!