com.gateway.connector.tcp.server.Connection Maven / Gradle / Ivy
package com.gateway.connector.tcp.server;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gateway.connector.utils.NetUtils;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
public class Connection {
private final static Logger logger = LoggerFactory.getLogger(Connection.class);
protected Session session = null;
protected String connectionId = null;
protected volatile boolean close = false;
protected int connectTimeout = 60 * 60 * 1000; // ms
public void fireError(Exception e) {
}
public boolean isClosed() {
return close;
}
public void setConnectionId(String connectionId) {
this.connectionId = connectionId;
}
public String getConnectionId() {
return connectionId;
}
public void setSession(Session session) {
this.session = session;
}
public Session getSession() {
return session;
}
private ChannelHandlerContext cxt;
public Connection(ChannelHandlerContext cxt) {
this.cxt = cxt;
}
public void connect() {
}
public void close() {
this.close = true;
cxt.close();
logger.debug("the connection have been destroyed! ctx -> " + cxt.toString());
}
public void send(Object message) {
if (message == null)
return;
sendMessage(message);
}
public boolean isWritable() {
return cxt.channel().isWritable();
}
private void sendMessage(Object message) {
if (isClosed()) {
Exception e = new Exception("Use a closed pushSocked!");
}
pushMessage0(message);
}
private String getRemoteAddress(ChannelHandlerContext ctx) {
SocketAddress remote1 = ctx.channel().remoteAddress();
InetSocketAddress remote = (InetSocketAddress) remote1;
return NetUtils.toAddressString(remote);
}
private void pushMessage0(Object message) {
try {
cxt.writeAndFlush(message);
session.access();
} catch (Exception e) {
logger.error("Connection pushMessage occur Exception.", e);
}
}
private void pushMessage(Object message) {
boolean success = true;
boolean sent = true;
int timeout = 60;
try {
ChannelFuture cf = cxt.write(message);
cxt.flush();
if (sent) {
success = cf.await(timeout);
}
if (cf.isSuccess()) {
logger.debug("send success.");
}
Throwable cause = cf.cause();
if (cause != null) {
this.fireError(new Exception(cause));
}
} catch (Exception e) {
logger.error("Connection pushMessage occur Exception.", e);
this.fireError(new Exception("ChannelFuture " + connectionId + " ", e));
}
if (!success) {
this.fireError(new Exception("Failed to send message, in timeout(" + timeout + "ms) limit"));
}
}
}