📄 connectionfactory.java
字号:
/**
* Created at Nov 22, 2008
*/
package com.jdev.net.connector;
import com.jdev.net.ClientHandler;
import com.jdev.net.ServerHandler;
import com.jdev.net.config.ServerCfg;
import com.jdev.net.event.Notifier;
import com.jdev.util.Debug;
/**
* <p>Title: ConnectionFactory</p>
* <p>Description: 连接工厂,用于获得Connection连接</p>
* @author Lawrence
* @version 1.0
*/
public class ConnectionFactory {
private final static String module = ConnectionFactory.class.getName();
public final static int CLIENT = 1;
public final static int TCPSERVER = 2;
public final static int UDPSERVER = 3;
private int fType; //是服务器端的还是CLient端
private static ConnectionFactory factory;
private TcpClient cclient = null;
private Reactor tserver = null;
public synchronized static ConnectionFactory getInstance(int fType) {
if (factory == null)
factory = new ConnectionFactory(fType);
return factory;
}
private ConnectionFactory(int fType) {
this.fType = fType;
}
public Connection getConnection() {
if (fType == CLIENT) {
startTcpClientSocket();
TcpConnection cli = new TcpConnection(fType);
cli.attach(cclient);
return cli;
} else {
startTcpServerSocket();
return new TcpConnection(fType);
}
}
/**
* 开启服务器端TCP Socket线程
*/
private void startTcpServerSocket() {
if (tserver != null)
return;
try {
ServerCfg cfg = new ServerCfg();
ServerHandler server = new ServerHandler();
Notifier notifier = Notifier.getNotifier();
notifier.addListener(server);
tserver = new Reactor(cfg.getTcpPort());
Thread thread = new Thread(tserver);
// thread.setDaemon(true);
thread.start();
Debug.logVerbose("--> started Tcp Server thread ..", module);
} catch (Exception ex) {
Debug.logError("started Tcp error:" + ex, module);
}
}
/**
* 开启客户端Tcp Socket线程
*/
private void startTcpClientSocket() {
if (cclient != null)
return;
try {
ClientHandler server = new ClientHandler();
Notifier notifier = Notifier.getNotifier();
notifier.addListener(server);
cclient = new TcpClient();
Thread thread = new Thread(cclient);
// thread.setDaemon(true);
thread.start();
Debug.logVerbose("--> started Tcp Socket thread ..", module);
} catch (Exception ex) {
Debug.logError("started Tcp error:" + ex, module);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -