來源:互聯網
上載者:User
關鍵字
socket用戶端
socket
js
php
socket用戶端socketjsphp
想用php做一個socket 用戶端,可以實現一次串連,然後多次給服務端發訊息。具體的想法是這樣的:
做一個頁面,這個頁面上有個按鈕和訊息列,點一下按鈕就可以把訊息列的內容發送給服務端,再點一下再發送,而不需要重新串連,只是頁面開啟時跟服務端串連上。
這個要怎麼實現呀?請各位大牛幫幫忙,小妹先謝過了。
附上socket類的代碼。
/** 定義ip,和連接埠 */
define ( 'PHP_SOCKET_PORT', '6000' );
define ( 'PHP_SOCKET_HOST', '127.0.0.1' );
define ( 'PHP_SOCKET_START', '' );
define ( 'PHP_SOCKET_END', '' );
// socket class
class socket{
var $socket; //socket 控制代碼
var $sendflag = ">>>";
var $recvflag = "<<<";
var $response;
var $debug = 1;
function socket($hostname,$port){
$address = gethostbyname($hostname);
$this->socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
$result = socket_connect($this->socket,$address,$port);
if($this->debug == 1){
if ($result < 0) {
$result = "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "
";
} else{
$result = "connect OK.
";
}
}
}
function sendmsg($msg){
socket_write($this->socket,$msg,strlen($msg));
$result = socket_read($this->socket,100);
$this->response = $result;
if($this->debug == 1){
printf("%s $msg
",$this->sendflag);
printf("%s $result
",$this->recvflag);
}
return $result;
}
function close(){
socket_close($this->socket);
}
}
?>