本文整理汇总了Java中java.nio.channels.SocketChannel.close方法的典型用法代码示例。如果您正苦于以下问题:Java SocketChannel.close方法的具体用法?Java SocketChannel.close怎么用?Java SocketChannel.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.nio.channels.SocketChannel
的用法示例。
在下文中一共展示了SocketChannel.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: handle
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void handle(SelectionKey key) {
SocketChannel channel = (SocketChannel) key.channel();
if (key.isConnectable()) {
try {
if (channel.finishConnect()) {
//connect finish
this.logger.info("[Connecter] finish connect " + channel.getRemoteAddress().toString());
IoWorker worker = this.workers.get(workersIndex);
worker.dispatch(new JobBean(channel, this.chanToParam.get(channel)));
workersIndex = (workersIndex + 1) % workers.size();
}
} catch (IOException e) {
this.logger.info("[Connecter] finish connect error : " + e.toString());
ClientParam clientParam = this.chanToParam.get(channel);
if (clientParam.getOnConnectError() != null) {
clientParam.getOnConnectError().onConnectError(e);
}
this.chanToParam.remove(channel);
try {
channel.close();
} catch (IOException e1) {
// already close
}
}
}
}
示例2: readData
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void readData() throws Exception {
buff.clear();
SocketChannel sc = (SocketChannel) sk.channel();
int count = -1;
while ((count = sc.read(buff)) > 0) {
// TODO - in the future pass this to a "listener" which will do something useful with this buffer
buff.clear();
}
if (count < 0) {
sc.close();
} else {
sk.interestOps(sk.interestOps() | SelectionKey.OP_READ);
}
sel.wakeup();
}
示例3: openConnection
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
/**
* out node try to connect
*
* @param node
*/
public void openConnection(Node node) {
SocketChannel channel = null;
try {
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.socket().setReuseAddress(true);
InetSocketAddress socketAddress = new InetSocketAddress(node.getIp(), node.getPort());
channel.connect(socketAddress);
PendingConnect data = new PendingConnect(channel, node);
SelectionKey key = channel.register(selector, SelectionKey.OP_CONNECT);
key.attach(data);
selector.wakeup();
} catch (IOException e) {
e.printStackTrace();
if (channel != null) {
try {
channel.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
node.destroy();
}
}
示例4: read
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
buffer.order(ByteOrder.LITTLE_ENDIAN);
int bytesRead;
try {
bytesRead = channel.read(buffer);
} catch (IOException exception) {
key.cancel();
channel.close();
if (this.rconSessions.contains(channel)) {
this.rconSessions.remove(channel);
}
if (this.sendQueues.containsKey(channel)) {
this.sendQueues.remove(channel);
}
return;
}
if (bytesRead == -1) {
key.cancel();
channel.close();
if (this.rconSessions.contains(channel)) {
this.rconSessions.remove(channel);
}
if (this.sendQueues.containsKey(channel)) {
this.sendQueues.remove(channel);
}
return;
}
buffer.flip();
this.handle(channel, new RCONPacket(buffer));
}
示例5: testConnectCallback
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
@Test
public void testConnectCallback() throws IOException {
eventLoop.registerAccept(acceptSocket, serverHandler);
SocketChannel clientSocket = SocketChannel.open();
clientSocket.configureBlocking(false);
boolean connected = clientSocket.connect(
new InetSocketAddress(InetAddress.getLocalHost(), serverPort));
assertFalse(connected);
assertTrue(clientSocket.isConnectionPending());
eventLoop.registerConnect(clientSocket, serverHandler);
// registering it for reading as well is not permitted: causes problems on Linux
try {
eventLoop.registerRead(clientSocket, serverHandler);
fail("expected exception");
} catch (AssertionError e) {}
// The event loop will trigger the accept callback
assertNull(serverHandler.client);
eventLoop.runOnce();
assertNotNull(serverHandler.client);
assertTrue(clientSocket.isConnectionPending());
// The event loop will also have triggered the connect callback
assertTrue(serverHandler.connected);
connected = clientSocket.finishConnect();
assertTrue(connected);
assertTrue(clientSocket.isConnected());
// Registering some other handler in response to the connect event should work
eventLoop.registerRead(clientSocket, new TestHandler());
clientSocket.close();
}
示例6: closeConnection
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static void closeConnection(SocketChannel connection) throws InterruptedException, IOException {
synchronized (m_executors) {
ExecutorPair p = m_executors.remove(connection);
assert(p != null);
p.shutdown();
}
connection.close();
}
示例7: handleInput
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
/** 对接收到的key进行处理
*@description 相关说明
*@time 创建时间:2017年7月17日下午2:55:56
*@param key
*@throws IOException
*@author dzn
*/
private void handleInput(SelectionKey key) throws IOException{
if(key.isValid()){
SocketChannel sc = (SocketChannel)key.channel();
if(key.isConnectable()){
if(sc.finishConnect()){
sc.register(this.selector, SelectionKey.OP_READ);
this.doWrite(sc);
}else{
System.exit(1);//连接失败,进程退出
}
}
if(key.isReadable()){
ByteBuffer bb = ByteBuffer.allocate(1024);
int readBytes = sc.read(bb);
if(readBytes > 0){
bb.flip();
byte[] bytes = new byte[bb.remaining()];
bb.get(bytes);
String body = new String(bytes, "UTF-8");
System.out.println("Now is " + body);
this.stop = true;
}else if(readBytes < 0){
key.cancel();
sc.close();
}else{
;// 读到0字节,忽略
}
}
}
}
示例8: write
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void write(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
synchronized (this.sendQueues) {
List<RCONPacket> queue = this.sendQueues.get(channel);
ByteBuffer buffer = queue.get(0).toBuffer();
try {
channel.write(buffer);
queue.remove(0);
} catch (IOException exception) {
key.cancel();
channel.close();
if (this.rconSessions.contains(channel)) {
this.rconSessions.remove(channel);
}
if (this.sendQueues.containsKey(channel)) {
this.sendQueues.remove(channel);
}
return;
}
if (queue.isEmpty()) {
this.sendQueues.remove(channel);
}
key.interestOps(SelectionKey.OP_READ);
}
}
示例9: switchToUSB
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static boolean switchToUSB(String deviceSerial) {
SocketChannel channel = openAdbConnection();
try {
if (send(channel, SELECT_DEVICE.replace("sn", deviceSerial))) {
return send(channel, SWITCH_TO_USB);
}
} finally {
try {
channel.close();
} catch (IOException ex) {
}
}
return false;
}
示例10: close
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
@Override
public void close(SelectionKey key) {
key.cancel();
SocketChannel sc = (SocketChannel) key.channel();
try {
sc.close();
logger.info("close client success");
} catch (IOException e) {
logger.error("close client error", e);
}
}
示例11: readFromKey
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static void readFromKey(
SelectionKey key, ByteBuffer readBuffer,
ByteArrayOutputStream bos, Consumer<byte[]> packetProcessor
) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
// Attempt to read off the channel
int numRead;
try {
numRead = socketChannel.read(readBuffer);
} catch (IOException e) {
LOG.error("", e);
key.cancel();
socketChannel.close();
return;
}
if (numRead == -1) {
// Remote entity shut the socket down cleanly. Do the
// same from our end and cancel the channel.
key.channel().close();
key.cancel();
} else {
processReadBuffer(readBuffer, bos, packetProcessor);
}
}
示例12: terminate
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
void terminate() {
SocketChannel socketChannel = _socketChannel;
try {
if (socketChannel != null) {
socketChannel.close();
}
} catch (Exception e) {
XulLog.e(TAG, e);
}
clear();
}
示例13: connectEthernet
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static boolean connectEthernet(String ipPort) {
SocketChannel channel = openAdbConnection();
try {
return send(channel, CONNECT_TCP_ALL + ipPort);
} finally {
try {
channel.close();
} catch (IOException ex) {
}
}
}
示例14: run
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public void run() {
SocketChannel sChannel = null;
try {
/*
* For future unwary socket programmers: although connect 'blocks' it
* does not require an accept on the server side to return. Therefore
* you can not assume that all the sockets are connected at the end of
* this for loop.
*/
sChannel = SocketChannel.open();
sChannel.connect(new InetSocketAddress(host,port));
// Construct a connection request
ConnectRequest conReq = new ConnectRequest(0, 0,
10000, 0, "password".getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
boa.writeInt(-1, "len");
conReq.serialize(boa, "connect");
baos.close();
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
bb.putInt(bb.capacity() - 4);
bb.rewind();
/* Send a connect request. Any socket that has been closed (or at least
* not added to the cnxn list on the server) will not have any bytes to
* read and get an eof.
*
* The trick here was finding a call that caused the server to put
* bytes in the input stream without closing the cnxn. None of
* the four letter commands do that, so we actually try to create
* a session which should send us something back, while maintaining
* the connection.
*/
int eof = sChannel.write(bb);
// If the socket times out, we count that as Assert.failed -
// the server should respond within 10s
sChannel.socket().setSoTimeout(10000);
if (!sChannel.socket().isClosed()){
eof = sChannel.socket().getInputStream().read();
if (eof != -1) {
numConnected.incrementAndGet();
}
}
}
catch (IOException io) {
// "Connection reset by peer"
}
finally {
if (sChannel != null) {
try {
sChannel.close();
}
catch (Exception e) {
}
}
}
}
示例15: doWork
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public void doWork() throws Exception {
for (; ; ) {
//TODO, stop the server (this loop and the executor) if there are no more connected sockets
while (sel.select() > 0)
;
Iterator it = sel.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey sk = (SelectionKey) it.next();
if (sk.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
SocketChannel sc = ssc.accept();
if (!sshMode) {// standalone mode
sc.configureBlocking(false);
sc.register(sel, SelectionKey.OP_READ);
} else {// SSH mode
if (allowedIP != null && !allowedIP.equals(sc.socket().getInetAddress().getHostAddress())) {
// just the IP passed on secured SSH control connection is allowed to connect
System.err.println(" [" + allowedIP + "] does not match " + sc.socket().getInetAddress().getHostAddress());
sc.close();
} else {// allowed connection
sc.configureBlocking(false);
sc.register(sel, SelectionKey.OP_READ);
if (--connectionNo == 0) {
// stop listening for other connection
this.ssc.keyFor(sel).cancel();
this.ssc.close();
}
}
}
} else if (sk.isReadable()) {
sk.interestOps(sk.interestOps() & ~SelectionKey.OP_READ);
executor.execute(new ReaderTask(sk));
}
it.remove();
}
}
}