TCP server socket

suggest change

Socket creation

Create a socket that uses the TCP. It is the same as creating a client socket.

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

Socket binding

Bind connections from a given network (parameter 2) for a specific port (parameter 3) to the socket.

The second parameter is usually "0.0.0.0", which accepts connection from all networks. It can also

One common cause of errors from socket_bind is that the address specified is already bound to another process. Other processes are usually killed (usually manually to prevent accidentally killing critical processes) so that the sockets would be freed.

socket_bind($socket, "0.0.0.0", 6667) or onSocketFailure("Failed to bind to 0.0.0.0:6667");

Set a socket to listening

Make the socket listen to incoming connections using socket_listen. The second parameter is the maximum number of connections to allow queuing before they are accepted.

socket_listen($socket, 5);

Handling connection

A TCP server is actually a server that handles child connections. socket_accept creates a new child connection.

$conn = socket_accept($socket);

Data transferring for a connection from socket_accept is the same as that for a http://stackoverflow.com/documentation/php/6138/sockets/23032/tcp-client-socket.

When this connection should be closed, call socket_close($conn); directly. This will not affect the original TCP server socket.

Closing the server

On the other hand, socket_close($socket); should be called when the server is no longer used. This will free the TCP address as well, allowing other processes to bind to the address.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Sockets:
* TCP server socket

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR