本文整理汇总了PHP中socket_bind函数的典型用法代码示例。如果您正苦于以下问题:PHP socket_bind函数的具体用法?PHP socket_bind怎么用?PHP socket_bind使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了socket_bind函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: start
public function start()
{
$host = $this->host;
$port = $this->port;
echo "app can be acessed from ws://{$host}:{$port}\n";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
$this->logLastError($socket, "1");
}
if (socket_bind($socket, $host, $port) === false) {
$this->logLastError($socket, "2");
}
if (socket_listen($socket, 5) === false) {
$this->logLastError($socket, "3");
}
$this->setServerSocket($socket);
$serverSocket = $this->getServerSocket();
do {
$sockets = $this->getSockets();
//Set up a blocking call to socket_select
$write = null;
$except = null;
$tv_sec = 5;
if (socket_select($sockets, $write, $except, $tv_sec) < 1) {
continue;
} else {
$this->setSockets($sockets);
}
//Handle new Connections
if ($this->hasSocket($serverSocket)) {
$clientSocket = socket_accept($serverSocket);
if ($clientSocket === false) {
$this->logLastError($serverSocket, "4");
} else {
$this->setClientSocket($clientSocket);
$response = "HTTP/1.1 101 Switching Protocols";
$this->respond($clientSocket, $response);
}
}
//Handle Input
foreach ($this->getClientSockets() as $clientSocket) {
if ($this->hasSocket($clientSocket)) {
$message = socket_read($clientSocket, 2048, PHP_NORMAL_READ);
if ($message === false) {
$this->logLastError($clientSocket, "5");
$this->removeSocket($clientSocket);
socket_close($clientSocket);
break;
} else {
$message = trim($message);
if (!empty($message)) {
$response = $this->trigger("message", ["{$message}"]);
$this->respond($clientSocket, $response);
}
}
}
}
} while (true);
socket_close($serverSocket);
}
示例2: bind
/**
* @throws \Exception
*/
public function bind()
{
$socketBind = @socket_bind($this->socket, $this->address, $this->port);
if (!$socketBind) {
throw new \Exception('socket could not be bound: ' . '(' . socket_last_error($this->socket) . ') ' . socket_strerror(socket_last_error($this->socket)));
}
}
示例3: __construct
public function __construct($MyProperties, $NodeList)
{
$this->MyProperties = $MyProperties;
$this->NodeList = $NodeList;
$this->Sender = new Sender($this->MyProperties);
$this->Reciever = new Reciever($this->NodeList);
$this->state = "Initialized";
$this->currentTerm = 0;
$this->votedFor = null;
$this->votes = 0;
$this->log = array();
$this->commitIndex = 0;
$this->lastApplied = 0;
$this->lastLogIndex = 0;
$this->nextIndex = array();
$this->matchIndex = array();
$this->timeoutinterval = 0.15;
$this->heartbeatinterval = 0.075;
$this->LeaderId = null;
$this->close = false;
$this->connectIndex = 0;
set_time_limit(0);
$this->socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
socket_bind($this->socket, $MyProperties->ServerAddr, $MyProperties->PortNo + count($NodeList->Nodes) + 1);
socket_listen($this->socket);
$this->clientSocket = false;
socket_set_nonblock($this->socket);
$this->exiting = false;
$this->exitcount = 0;
}
示例4: lw_start
function lw_start()
{
if ($this->Server['Started'] !== false) {
return false;
}
if (($this->Handler = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
$this->lw_log('socket_create() failed: reason: ' . socket_strerror(socket_last_error($this->Handler)));
return false;
} else {
$this->lw_log('Socket created');
}
socket_set_nonblock($this->Handler);
if (($ret = socket_bind($this->Handler, $this->Options['Address'], $this->Options['Port'])) !== true) {
$this->lw_log('socket_bind() failed: reason: ' . socket_strerror(socket_last_error($this->Handler)));
return false;
} else {
$this->lw_log('Socket bindet');
}
if (socket_listen($this->Handler, isset($this->Options['ConnectLimit']) ? $this->Options['ConnectLimit'] : 5) !== true) {
$this->lw_log('socket_listen() failed: reason: ' . socket_strerror(socket_last_error($this->Handler)));
return false;
}
//socket_set_option($this->Handler,SOL_SOCKET,SO_KEEPALIVE,2);
//echo 'SO_KEEPALIVE : '.socket_get_option($this->Handler,SOL_SOCKET,SO_KEEPALIVE).RN;
//echo 'SO_REUSEADDR : '.socket_get_option($this->Handler,SOL_SOCKET,SO_REUSEADDR).RN;
//echo 'SO_RCVBUF : '.socket_get_option($this->Handler,SOL_SOCKET,SO_RCVBUF).RN;
//echo 'SO_SNDBUF : '.socket_get_option($this->Handler,SOL_SOCKET,SO_SNDBUF).RN;
//echo 'SO_DONTROUTE : '.socket_get_option($this->Handler,SOL_SOCKET,SO_DONTROUTE).RN;
//echo 'SOCKET_EHOSTUNREACH : '.SOCKET_EHOSTUNREACH.RN;
//echo 'SO_BROADCAST : '.socket_get_option($this->Handler,SOL_SOCKET,SO_BROADCAST).RN;
$this->Server['Started'] = microtime(true);
/// php 5
// wb_create_timer ($_CONTROL['window'], $_SERVER['timer'][0], CL_SOCKET_TIMER);
return true;
}
示例5: create
/**
* Create a Socket Server on the given domain and port
* @param $domain String
* @param $port Float[optional]
*/
function create($domain, $port = 9801)
{
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($this->socket, $domain, $port);
socket_listen($this->socket);
socket_set_block($this->socket);
}
示例6: create
/**
* Create server
* - bind to port
* - listen port
* @throws ListenException
* @throws BindException
*/
function create($blocking = true)
{
$this->open();
$serverSocket = $this->getSocketResource();
if (!socket_bind($serverSocket, $this->getIp(), $this->getPort())) {
throw new BindException($this);
}
$this->getEventDispatcher()->dispatch(BindEvent::getEventName(), new BindEvent($this, $this));
if (!socket_listen($serverSocket)) {
throw new ListenException($this);
}
if ($blocking) {
socket_set_block($serverSocket);
} else {
socket_set_nonblock($serverSocket);
}
$this->start();
while ($this->running) {
$clientSocket = socket_accept($serverSocket);
if (false == $clientSocket) {
continue;
}
$socket = new Socket($this->getAddressType(), $this->getSocketType(), $this->getTransport(), $this->getEventDispatcher());
$socket->setSocketResource($clientSocket);
$socket->getEventDispatcher()->dispatch(NewConnectionEvent::getEventName(), new NewConnectionEvent($socket, $this));
}
}
示例7: listen
/**
* Começa a escutar conexões e processar as demais funcionalidades
* @param int $port número da porta
* @throws EndPointException
*/
public function listen($port)
{
$this->port = $port;
/* @var resource cria o socket que escutará conexões */
$this->serverSocket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('TCP'));
if (!socket_set_option($this->serverSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo socket_strerror(socket_last_error($this->serverSocket));
exit;
}
/* seta o host e a porta */
if (!@socket_bind($this->serverSocket, 0, $this->port)) {
throw new EndPointException("socket_bind() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket)));
}
/* inicia a escuta de conexões */
if (!@socket_listen($this->serverSocket)) {
throw new EndPointException("socket_listen() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket)));
}
/* cria um array de sockets e adiciona o serverSocket no array */
$this->sockets = array($this->serverSocket);
$this->loopPrincipal();
/* Fecha todos os sockets e encerra a aplicação */
foreach ($this->sockets as $socket) {
if (get_resource_type($socket) == "Socket") {
socket_close($socket);
}
}
}
示例8: udp
public function udp()
{
set_time_limit(0);
$ip = '127.0.0.1';
$port = 9527;
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, $ip, $port);
$mem = init_mem();
if ($mem == false) {
return;
}
while (true) {
socket_recvfrom($socket, $content, 1024, 0, $ip, $port);
if (empty($content)) {
continue;
}
//$this->log_data($content);
$minute = (int) date("i");
$datagram = $mem->get('datagram');
if (empty($datagram)) {
$datagram = array();
}
$datagram[$minute][] = $content;
$mem->set('datagram', $datagram);
}
socket_close($socket);
$mem->close();
}
示例9: createSocket
private function createSocket()
{
$this->serverSocket = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($this->serverSocket, 0, $this->port) or die("bind error !!");
socket_listen($this->serverSocket);
$this->waitSocket();
}
示例10: start
public function start()
{
self::$_logger->info('Server starts.');
// Init a non-blocking TCP socket for listening
$this->_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$this->_sock) {
$errno = socket_last_error();
$errstr = socket_strerror($errno);
self::$_logger->err("Socket create error: {$errstr} ({$errno})");
die;
}
socket_set_nonblock($this->_sock);
if (!socket_bind($this->_sock, $this->_addr, $this->_port)) {
$errno = socket_last_error();
$errstr = socket_strerror($errno);
self::$_logger->err("Socket bind error: {$errstr} ({$errno})");
die;
}
if (!socket_listen($this->_sock, $this->_listenQueue)) {
$errno = socket_last_error();
$errstr = socket_strerror($errno);
self::$_logger->err("Socket listen error: {$errstr} ({$errno})");
die;
}
// For the listening socket, we use raw event to handle it.
$this->_listenEvent = event_new();
event_set($this->_listenEvent, $this->_sock, EV_READ | EV_PERSIST, array($this, 'handleAcceptEvent'));
event_base_set($this->_listenEvent, $this->_eventBase);
event_add($this->_listenEvent);
// Endless loop
$this->_started = TRUE;
event_base_loop($this->_eventBase);
// The loop ends here.
$this->stop();
}
示例11: start
public function start()
{
//确保在连接客户端时不会超时
echo "1";
set_time_limit(0);
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() 建立失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
//阻塞模式
echo "2";
socket_set_block($this->socket) or die("socket_set_block() 阻塞失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
//绑定到socket端口
echo "3";
$result = socket_bind($this->socket, $this->address, 5062) or die("socket_bind() 绑定失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
//开始监听
echo "4";
$result = socket_listen($this->socket, 4) or die("socket_listen() 监听失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
echo "Begin listining";
do {
// never stop the daemon
//它接收连接请求并调用一个子连接Socket来处理客户端和服务器间的信息
$msgsock = socket_accept($this->socket) or die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
//读取客户端数据
echo "Read client data \n";
//socket_read函数会一直读取客户端数据,直到遇见\n,\t或者\0字符.PHP脚本把这写字符看做是输入的结束符.
$buf = socket_read($msgsock, 21000);
echo "Received msg: {$buf} \n";
//数据传送 向客户端写入返回结果
$msg = "welcome \n";
socket_write($msgsock, $msg, strlen($msg)) or die("socket_write() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
//一旦输出被返回到客户端,父/子socket都应通过socket_close($msgsock)函数来终止
socket_close($msgsock);
} while (true);
socket_close($this->socket);
}
示例12: bind_socket
public function bind_socket()
{
if (socket_bind($this->sock, $this->address, $this->port) === false) {
return false;
}
return true;
}
示例13: server_loop
/**
* Creates a server socket and listens for incoming client connections
* @param string $address The address to listen on
* @param int $port The port to listen on
*/
function server_loop($address, $port)
{
global $__server_listening;
if (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
echo "failed to create socket: " . socket_strerror($sock) . "\n";
exit;
}
if (($ret = socket_bind($sock, $address, $port)) < 0) {
echo "failed to bind socket: " . socket_strerror($ret) . "\n";
exit;
}
if (($ret = socket_listen($sock, 0)) < 0) {
echo "failed to listen to socket: " . socket_strerror($ret) . "\n";
exit;
}
socket_set_nonblock($sock);
echo "waiting for clients to connect\n";
while ($__server_listening) {
$connection = @socket_accept($sock);
if ($connection === false) {
usleep(100);
} elseif ($connection > 0) {
handle_client($sock, $connection);
} else {
echo "error: " . socket_strerror($connection);
die;
}
}
}
示例14: mServer
public function mServer()
{
$sock = socket_create(AF_INET, SOCK_DGRAM, getprotobyname('udp'));
$mIP = '239.255.255.250';
if (!socket_bind($sock, $mIP, 1900)) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [{$errorcode}] {$errormsg} \n");
}
socket_set_option($sock, IPPROTO_IP, MCAST_JOIN_GROUP, array("group" => '239.255.255.250', "interface" => 0));
while (1) {
echo "Waiting for data ... \n";
socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
echo "{$remote_ip} : {$remote_port} -- " . $buf;
$query = $this->parseHeaders($buf);
if (!isset($query["m-search"])) {
continue;
}
$response = "HTTP/1.1 200 OK\r\n";
$response .= "CACHE-CONTROL: max-age=1810\r\n";
$response .= "DATE: " . date("r") . "\r\n";
$response .= "EXT:\r\n";
$response .= "LOCATION: http://192.168.7.123:9000/TMSDeviceDescription.xml\r\n";
$response .= "SERVER: Linux/3.x, UPnP/1.1, fheME/0.6\r\n";
$response .= "ST: urn:fheme.de:service:X_FIT_HomeAutomation:1\r\n";
$response .= "USN: uuid:f6da16ab-0d1b-fe1c-abca-82aacf4afcac::urn:fheme.de:service:X_FIT_HomeAutomation:1\r\n";
$response .= "Content-Length: 0\r\n";
$response .= "\r\n";
//Send back the data to the client
socket_sendto($sock, $response, strlen($response), 0, $mIP, $remote_port);
}
socket_close($sock);
}
示例15: init
public function init()
{
if ($this->initialized) {
return NULL;
}
$this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->socket === false) {
$this->setError($this->getSocketError("Failed creating socket"), LOG_ERR);
return false;
}
if (!socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
$this->setError($this->getSocketError("Failed setting SO_REUSEADDR on socket"), LOG_ERR);
return false;
}
if (!@socket_bind($this->socket, $this->server_address, $this->server_port)) {
$this->setError($this->getSocketError("Failed binding socket to " . $this->server_address . ":" . $this->server_port), LOG_ERR);
return false;
}
if (!@socket_listen($this->socket, 5)) {
$this->setError($this->getSocketError("Failed starting to listen on socket"), LOG_ERR);
return false;
}
socket_set_nonblock($this->socket);
return $this->initialized = true;
}