本文整理匯總了Java中io.netty.channel.Channel類的典型用法代碼示例。如果您正苦於以下問題:Java Channel類的具體用法?Java Channel怎麽用?Java Channel使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Channel類屬於io.netty.channel包,在下文中一共展示了Channel類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: scanNotActiveChannel
import io.netty.channel.Channel; //導入依賴的package包/類
public void scanNotActiveChannel(){
try {
if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
for(Entry<String,Set<Channel>> entry : groupChannelTable.entrySet()){
if(CollectionUtils.isEmpty(entry.getValue())){
continue;
}
Iterator<Channel> it = entry.getValue().iterator();
while(it.hasNext()){
Channel c = it.next();
if(!c.isActive()){
it.remove();
}
}
}
}else {
log.warn("ProducerManager scanNotActiveChannel lock timeout");
}
} catch (Exception e) {
log.error("scanNotActiveChannel",e);
}finally{
this.groupChannelLock.unlock();
}
}
示例2: connectToLocal
import io.netty.channel.Channel; //導入依賴的package包/類
public NetworkDispatcher connectToLocal(SocketAddress address)
{
NetworkDispatcher dispatch = new NetworkDispatcher(this, NetworkSide.CLIENT);
final EventLoopGroup boss = new DefaultEventLoopGroup();
final Bootstrap b = new Bootstrap()
.group(boss)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception
{
ch.pipeline().addLast(dispatch);
}
})
.channel(LocalChannel.class);
//Connect and wait until done
b.connect(address).syncUninterruptibly();
return dispatch;
}
示例3: start
import io.netty.channel.Channel; //導入依賴的package包/類
public static boolean start(Channel channel, String name, Logger logger) {
final PacketEncoder oldEncoder = channel.pipeline().get(PacketEncoder.class);
final PacketDecoder oldDecoder = channel.pipeline().get(PacketDecoder.class);
channel.eventLoop().execute(() -> {
if(channel.isOpen()) {
if(oldEncoder != null) {
channel.pipeline().replace(oldEncoder, "encoder", new Encoder(logger, name));
}
if(oldDecoder != null) {
channel.pipeline().replace(oldDecoder, "decoder", new Decoder(logger, name));
}
}
});
return oldEncoder != null || oldDecoder != null;
}
示例4: writeAndSync
import io.netty.channel.Channel; //導入依賴的package包/類
public ReplyMsg writeAndSync(final Channel channel, final AskMsg askMsg, final long timeout) throws Exception {
if (channel == null) {
throw new NullPointerException("channel");
}
if (askMsg == null) {
throw new NullPointerException("askMsg");
}
if (timeout <= 0) {
throw new IllegalArgumentException("timeout <= 0");
}
String requestId = UUID.randomUUID().toString();
askMsg.setRequestId(requestId);
WriteFuture<BaseMsg> future = new SyncWriteFuture(askMsg.getRequestId());
SyncWriteMap.syncKey.put(askMsg.getRequestId(), future);
System.out.println("發起請求,請求id:" + requestId + ",請求參數:" + askMsg.getData());
ReplyMsg response = doWriteAndSync(channel, askMsg, timeout, future);
SyncWriteMap.syncKey.remove(askMsg.getRequestId());
return response;
}
示例5: handleRegisterRequest
import io.netty.channel.Channel; //導入依賴的package包/類
@Override
protected void handleRegisterRequest(RegisterRequestMessage request,
Channel channel) {
try {
Scope scope = TProtocolUtil.getScope(request.store.getScope());
if (request.store.isPersist())
syncManager.registerPersistentStore(request.store.storeName,
scope);
else
syncManager.registerStore(request.store.storeName, scope);
RegisterResponseMessage m = new RegisterResponseMessage();
AsyncMessageHeader header = new AsyncMessageHeader();
header.setTransactionId(request.getHeader().getTransactionId());
m.setHeader(header);
SyncMessage bsm =
new SyncMessage(MessageType.REGISTER_RESPONSE);
bsm.setRegisterResponse(m);
channel.writeAndFlush(bsm);
} catch (Exception e) {
channel.writeAndFlush(getError(request.getHeader().getTransactionId(), e,
MessageType.REGISTER_REQUEST));
}
}
示例6: preCreateConnections
import io.netty.channel.Channel; //導入依賴的package包/類
@Override
public void preCreateConnections(final int count)
throws ConnectException, IllegalArgumentException {
if(count > 0) {
for(int i = 0; i < count; i ++) {
final Channel conn = connectToAnyNode();
if(conn == null) {
throw new ConnectException(
"Failed to pre-create the connections to the target nodes"
);
}
final String nodeAddr = conn.attr(ATTR_KEY_NODE).get();
if(conn.isActive()) {
final Queue<Channel> connQueue = availableConns.get(nodeAddr);
if(connQueue != null) {
connQueue.add(conn);
}
} else {
conn.close();
}
}
LOG.info("Pre-created " + count + " connections");
} else {
throw new IllegalArgumentException("Connection count should be > 0, but got " + count);
}
}
示例7: handshake
import io.netty.channel.Channel; //導入依賴的package包/類
protected void handshake(HelloMessage request, Channel channel) {
try {
switch (getAuthScheme()) {
case CHALLENGE_RESPONSE:
handshakeChallengeResponse(request, channel);
break;
case NO_AUTH:
// shouldn't get here
break;
}
} catch (AuthException e) {
logger.warn("[{}->{}] Failed to authenticate connection: {}",
new Object[]{getLocalNodeIdString(),
getRemoteNodeIdString(),
e.getMessage()});
channel.writeAndFlush(getError(request.getHeader().getTransactionId(),
e, MessageType.HELLO));
channel.close();
}
}
示例8: addLocalEndpoint
import io.netty.channel.Channel; //導入依賴的package包/類
/**
* Adds a channel that listens locally
*/
public SocketAddress addLocalEndpoint()
{
ChannelFuture channelfuture;
synchronized (this.endpoints)
{
channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
{
protected void initChannel(Channel p_initChannel_1_) throws Exception
{
NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
NetworkSystem.this.networkManagers.add(networkmanager);
p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
}
}).group((EventLoopGroup)eventLoops.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
this.endpoints.add(channelfuture);
}
return channelfuture.channel().localAddress();
}
示例9: accessibleChannel
import io.netty.channel.Channel; //導入依賴的package包/類
/**
* 對準備接入的 Channel 做進一步處理
*
* @param channel 準備接入的 Channel
*/
public void accessibleChannel(Channel channel) {
String id = channel.id().asLongText();
logger.info("「Channel」" + "新的 Channel 接入 [" + id + "]");
CHANNEL_MAP.put(id, -1);
HASHED_WHEEL_TIMER.newTimeout(task -> {
Integer index = CHANNEL_MAP.get(id);
if (index == -1) {
logger.warn("「Channel」" + "新的 Channel 未反饋 ID [" + id + "]");
channel.disconnect();
} else if (index > 0 && index <= DeviceSetting.MAX_GROUP_ID) {
SENDING_MESSAGE_QUEUE.get(index).clear();
Channel oldChannel = CHANNEL_ARRAY.get(index);
if (oldChannel != null && oldChannel.isActive()) {
manualRemoveChannel(CHANNEL_ARRAY.get(index));
manualRemoveChannel(channel);
logger.warn("「Channel」" + "新的 Channel 欲覆蓋已激活的 Channel [" + id + "]");
} else {
CHANNEL_ARRAY.set(index, channel);
logger.info("「Channel」" + "新的 Channel「" + index + "」已成功裝配 [" + id + "]");
}
} else {
logger.warn("「Channel」" + "新的 Channel 裝配出錯 [" + id + "]");
}
}, CommSetting.ACCESSIBLE_CHANNEL_REPLY_INTERVAL, TimeUnit.SECONDS);
}
示例10: createEventLoopGroup
import io.netty.channel.Channel; //導入依賴的package包/類
private static Pair<EventLoopGroup, Class<? extends Channel>> createEventLoopGroup(
Configuration conf) {
// Max amount of threads to use. 0 lets Netty decide based on amount of cores
int maxThreads = conf.getInt(CLIENT_MAX_THREADS, 0);
// Config to enable native transport. Does not seem to be stable at time of implementation
// although it is not extensively tested.
boolean epollEnabled = conf.getBoolean(USE_NATIVE_TRANSPORT, false);
// Use the faster native epoll transport mechanism on linux if enabled
if (epollEnabled && JVM.isLinux() && JVM.isAmd64()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Create EpollEventLoopGroup with maxThreads = " + maxThreads);
}
return new Pair<EventLoopGroup, Class<? extends Channel>>(new EpollEventLoopGroup(maxThreads,
Threads.newDaemonThreadFactory("AsyncRpcChannel")), EpollSocketChannel.class);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Create NioEventLoopGroup with maxThreads = " + maxThreads);
}
return new Pair<EventLoopGroup, Class<? extends Channel>>(new NioEventLoopGroup(maxThreads,
Threads.newDaemonThreadFactory("AsyncRpcChannel")), NioSocketChannel.class);
}
}
示例11: fixHandlerBeforeConnect
import io.netty.channel.Channel; //導入依賴的package包/類
/**
* 適配
*/
@Override
protected ChannelHandler fixHandlerBeforeConnect(final ChannelHandler handler) {
ChannelHandler result=new ShareableChannelInboundHandler() {
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
Channel ch=ctx.channel();
ch.pipeline().addLast(new HttpClientCodec());
ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
ctx.pipeline().remove(this);//移除當前handler
ctx.pipeline().fireChannelRegistered();//重新從第一個handler拋出事件
}
};
// ChannelInitializer<SocketChannel> result=new ChannelInitializer<SocketChannel>() {
// @Override
// protected void initChannel(SocketChannel ch) {
// ch.pipeline().addLast(new HttpClientCodec());
// ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
// ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
// ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
// }
// };
return result;
}
示例12: notifyConsumerIdsChanged
import io.netty.channel.Channel; //導入依賴的package包/類
/**
* Broker主動通知Consumer,Id列表發生變化,Oneway
*/
public void notifyConsumerIdsChanged(
final Channel channel,
final String consumerGroup) {
if (null == consumerGroup) {
log.error("notifyConsumerIdsChanged consumerGroup is null");
return;
}
NotifyConsumerIdsChangedRequestHeader requestHeader = new NotifyConsumerIdsChangedRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
RemotingCommand request =
RemotingCommand.createRequestCommand(RequestCode.NOTIFY_CONSUMER_IDS_CHANGED, requestHeader);
try {
this.brokerController.getRemotingServer().invokeOneway(channel, request, 10);
} catch (Exception e) {
log.error("notifyConsumerIdsChanged exception, " + consumerGroup, e.getMessage());
}
}
示例13: getAllClientId
import io.netty.channel.Channel; //導入依賴的package包/類
public List<String> getAllClientId() {
List<String> result = new ArrayList<>();
Iterator<Entry<Channel, ClientChannelInfo>> it = this.channelInfoTable.entrySet().iterator();
while (it.hasNext()) {
Entry<Channel, ClientChannelInfo> entry = it.next();
ClientChannelInfo clientChannelInfo = entry.getValue();
result.add(clientChannelInfo.getClientId());
}
return result;
}
示例14: invokeAsyncImpl
import io.netty.channel.Channel; //導入依賴的package包/類
/**
* 異步調用
* @param channel
* @param request
* @param timeoutMillis
* @param invokeCallback
* @throws InterruptedException
* @throws RemotingTooMuchRequestException
* @throws RemotingTimeoutException
* @throws RemotingSendRequestException
*/
@SuppressWarnings("rawtypes")
public void invokeAsyncImpl(final Channel channel, final RemotingProtocol request, final long timeoutMillis, final InvokeCallback invokeCallback) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
final long opaque = request.getOpaque();
// boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
final SemaphoreOnce once = new SemaphoreOnce(this.semaphoreAsync);
final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, invokeCallback, once);
responseTable.put(opaque, responseFuture);
try {
channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
//此步代表發送操作成功 設置的sendrequest值是為了區分發送失敗還是服務端處理失敗的
if (f.isSuccess()) {
responseFuture.setSendRequestOK(true);
return;
} else {
responseFuture.setSendRequestOK(false);
}
responseFuture.putResponse(null);
responseTable.remove(opaque);
// try {
// executeInvokeCallback(responseFuture);
// } catch (Throwable e) {
// logger.warn("excute callback in writeAndFlush addListener, and callback throw", e);
// } finally {
// responseFuture.release();
// }
logger.warn("send a request command to channel <{}> failed.", RemotingHelper.parseChannelRemoteAddr(channel));
}
});
} catch (Exception e) {
responseFuture.release();
logger.warn("send a request command to channel <" + RemotingHelper.parseChannelRemoteAddr(channel) + "> Exception", e);
throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
}
}
示例15: registerClienId
import io.netty.channel.Channel; //導入依賴的package包/類
public static void registerClienId(String clientId, Channel chn) {
if (chn == null) {
return;
}
if (clientId == null) {
return;
}
chn.closeFuture().addListener(clientRemover);
channelClientIdMap.put(chn, clientId);
ChannelEntity oldChannel = cientIdChannelMap.put(clientId, new TcpChannelEntity(chn));
if (oldChannel != null) {
removeChannel(oldChannel.getChannel());
oldChannel.getChannel().close();
}
}