EventBufferEvent::connect

(PECL event >= 1.2.6-beta)

EventBufferEvent::connectConnect buffer event's file descriptor to given address or UNIX socket

Beschreibung

public EventBufferEvent::connect( string $addr ): bool

Connect buffer event's file descriptor to given address(optionally with port), or a UNIX domain socket.

If socket is not assigned to the buffer event, this function allocates a new socket and makes it non-blocking internally.

To resolve DNS names(asyncronously), use EventBufferEvent::connectHost() method.

Parameter-Liste

addr

Should contain an IP address with optional port number, or a path to UNIX domain socket. Recognized formats are:

[IPv6Address]:port
[IPv6Address]
IPv6Address
IPv4Address:port
IPv4Address
unix:path
Note, 'unix:' prefix is currently not case sensitive.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Beispiele

Beispiel #1 EventBufferEvent::connect() example

<?php
/*
 * 1. Connect to 127.0.0.1 at port 80
 * by means of EventBufferEvent::connect().
 *
 * 2. Request /index.cphp via HTTP/1.0
 * using the output buffer.
 *
 * 3. Asyncronously read the response and print it to stdout.
 */

/* Read callback */
function readcb($bev$base) {
    
$input $bev->getInput();

    while ((
$n $input->remove($buf1024)) > 0) {
        echo 
$buf;
    }
}

/* Event callback */
function eventcb($bev$events$base) {
    if (
$events EventBufferEvent::CONNECTED) {
        echo 
"Connected.\n";
    } elseif (
$events & (EventBufferEvent::ERROR EventBufferEvent::EOF)) {
        if (
$events EventBufferEvent::ERROR) {
            echo 
"DNS error: "$bev->getDnsErrorString(), PHP_EOL;
        }

        echo 
"Closing\n";
        
$base->exit();
        exit(
"Done\n");
    }
}

$base = new EventBase();

echo 
"step 1\n";
$bev = new EventBufferEvent($base/* use internal socket */ NULL,
    
EventBufferEvent::OPT_CLOSE_ON_FREE EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!
$bev) {
    exit(
"Failed creating bufferevent socket\n");
}

echo 
"step 2\n";
$bev->setCallbacks("readcb"/* writecb */ NULL"eventcb"$base);
$bev->enable(Event::READ Event::WRITE);

echo 
"step 3\n";
/* Send request */
$output $bev->getOutput();
if (!
$output->add(
    
"GET /index.cphp HTTP/1.0\r\n".
    
"Connection: Close\r\n\r\n"
)) {
    exit(
"Failed adding request to output buffer\n");
}

/* Connect to the host syncronously.
 * We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
    exit(
"Can't connect to host\n");
}

/* Dispatch pending events */
$base->dispatch();

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

step 1
step 2
step 3
Connected.
HTTP/1.1 200 OK
Server: nginx/1.2.6
Date: Sat, 09 Mar 2013 10:06:58 GMT
Content-Type: text/html; charset=utf-8
Connection: close
X-Powered-By: PHP/5.4.11--pl2-gentoo

sdfsdfsf
Closing
Done

Beispiel #2 Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console

<?php
class MyUnixSocketClient {
    private 
$base$bev;

    function 
__construct($base$sock_path) {
        
$this->base $base;
        
$this->bev = new EventBufferEvent($baseNULLEventBufferEvent::OPT_CLOSE_ON_FREE,
            array (
$this"read_cb"), NULL, array ($this"event_cb"));

        if (!
$this->bev->connect("unix:$sock_path")) {
            
trigger_error("Failed to connect to socket `$sock_path'"E_USER_ERROR);
        }

        
$this->bev->enable(Event::READ);
    }

    function 
__destruct() {
        if (
$this->bev) {
            
$this->bev->free();
            
$this->bev NULL;
        }
    }

    function 
dispatch() {
        
$this->base->dispatch();
    }

    function 
read_cb($bev$unused) {
        
$in $bev->input;

        
printf("Received %ld bytes\n"$in->length);
        
printf("----- data ----\n");
        
printf("%ld:\t%s\n", (int) $in->length$in->pullup(-1));

        
$this->bev->free();
        
$this->bev NULL;
        
$this->base->exit(NULL);
    }

    function 
event_cb($bev$events$unused) {
        if (
$events EventBufferEvent::ERROR) {
            echo 
"Error from bufferevent\n";
        }

        if (
$events & (EventBufferEvent::EOF EventBufferEvent::ERROR)) {
            
$bev->free();
            
$bev NULL;
        } elseif (
$events EventBufferEvent::CONNECTED) {
            
$bev->output->add("test\n");
        }
    }
}

if (
$argc <= 1) {
    exit(
"Socket path is not provided\n");
}
$sock_path $argv[1];

$base = new EventBase();
$cl = new MyUnixSocketClient($base$sock_path);
$cl->dispatch();
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Received 5 bytes
----- data ----
5:  test

Siehe auch

Hier Kannst Du einen Kommentar verfassen


Bitte gib mindestens 10 Zeichen ein.
Wird geladen... Bitte warte.
* Pflichtangabe
Es sind noch keine Kommentare vorhanden.

Was genau bedeutet "Vibe Coding"? Ein tiefgehender Blick für Entwickler

In der Welt der Softwareentwicklung gibt es unzählige Wege, wie man an ein Projekt herangeht. Manche schwören auf strikte Planung, andere auf bewährte Algorithmen und wieder andere lassen sich von etwas ganz anderem leiten: ihrem Gefühl. ...

admin

Autor : admin
Kategorie: Software & Web-Development

PHP cURL-Tutorial: Verwendung von cURL zum Durchführen von HTTP-Anfragen

cURL ist eine leistungsstarke PHP-Erweiterung, die es Ihnen ermöglicht, mit verschiedenen Servern über verschiedene Protokolle wie HTTP, HTTPS, FTP und mehr zu kommunizieren. ...

TheMax

Autor : TheMax
Kategorie: PHP-Tutorials

Midjourney Tutorial - Anleitung für Anfänger

Über Midjourney, dem Tool zur Erstellung digitaler Bilder mithilfe von künstlicher Intelligenz, gibt es ein informatives Video mit dem Titel "Midjourney Tutorial auf Deutsch - Anleitung für Anfänger" ...

Mike94

Autor : Mike94
Kategorie: KI Tutorials

Tutorial veröffentlichen

Tutorial veröffentlichen

Teile Dein Wissen mit anderen Entwicklern weltweit

Du bist Profi in deinem Bereich und möchtest dein Wissen teilen, dann melde dich jetzt an und teile es mit unserer PHP-Community

mehr erfahren

Tutorial veröffentlichen

"Baustellen" endlich angehen?

Hey! Good on you for tackling those projects. Lockdown definitely offers a chance to get things done. I'm using the time to finally organize my sp ...

Geschrieben von Coreyalmer am 30.01.2026 04:56:38
Forum: Off-Topic Diskussionen
Löschen nach einen gewissen Datum in einer TXT-Datenbank

It's common situation, especially when a text file keeps growing over time. Removing entries based on a date sounds like a sensible way to keep th ...

Geschrieben von kumarbr am 29.01.2026 14:40:18
Forum: Off-Topic Diskussionen
Große JSON-Dateien in PHP effizient streamen?

Don’t use json_decode() for GB-scale files. Use a streaming parser (SAX-style) like jsonstreamingparser, or redesign the JSON into newline-delim ...

Geschrieben von jackmarvia689 am 28.01.2026 10:41:56
Forum: PHP Developer Forum
Kalenderwoche auf Sonntag anfangen lassen

The heart of Udaipur is City Palace, a magnificent complex overlooking Lake Pichola. With its balconies, courtyards, and museums, the palace offer ...

Geschrieben von dehradunbite am 28.01.2026 08:48:33
Forum: PHP Developer Forum