Questions And Answers

More Tutorials

PHP TCP server socket

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 "", 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, "", 6667) or onSocketFailure("Failed to bind to");

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 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.


In this page (written and validated by ) you learned about PHP TCP server socket . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP UDP server socket.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.