本文整理汇总了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();
}
}