我一直在使用PHP和MySQL开展一个小项目.我已经阅读了很多关于管理连接的最佳实践等等.
我还实现了(在一些帖子后面发现)一个单例类来管理MySQL连接.
require_once 'config.inc.php';
class DbConn {
private static $instance;
private $dbConn;
private function __construct() {}
/**
*
* @return DbConn
*/
private static function getInstance(){
if (self::$instance == null){
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
/**
*
* @return DbConn
*/
private static function initConnection(){
$db = self::getInstance();
$connConf = getConfigData();
$db->dbConn = new mysqli($connConf['db_host'], $connConf['db_user'], $connConf['db_pwd'],$connConf['db_name']);
$db->dbConn->set_charset('utf8');
return $db;
}
/**
* @return mysqli
*/
public static function getDbConn() {
try {
$db …Run Code Online (Sandbox Code Playgroud) 我需要将一些数据从主线程发送到另一个线程。我已经阅读了很多关于线程、异步任务和处理程序的材料,但也许它们给我带来了一些困惑。我读到我需要为我的“第二个线程”创建一个处理程序,以便我可以从主线程向它发送消息(现在我不担心将任何内容发送回主线程)。
我需要第二个线程连接到服务器(通过套接字)并在某些用户事件上发送一些日期。我正在尝试以有效的方式执行此操作(不要打开/关闭不必要的套接字连接)。所以我想知道我应该把我的打开套接字命令放在哪里?此外,在我的处理程序的 handleMessage() 方法中,我需要对套接字输出流的引用,以便将数据发送到服务器。
我目前有以下代码:
protected void initThread(){
this.thread = new HandlerThread(WorkerHandler.class.getCanonicalName()){
@Override
public void run() {
super.run();
try{
handler = new WorkerHandler(getLooper());
}catch(Exception e){
e.printStackTrace();
}
}
};
this.thread.start();
}
Run Code Online (Sandbox Code Playgroud)
initThread() 方法在我的活动的 onCreate() 方法中调用。
下面是我的自定义处理程序类的代码:
public class WorkerHandler extends Handler {
protected Socket socket;
protected BufferedWriter writer;
public WorkerHandler(Looper looper) throws Exception{
super(looper);
this.socket = new Socket("192.168.1.7", 5069);
this.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream(), "utf-8"));
}
public BufferedWriter getWriter(){
return this.writer;
}
public Socket getSocket(){
return this.socket;
}
@Override
public …Run Code Online (Sandbox Code Playgroud)