PHP Sockets Tutorial

Creator:
Michael4

This tutorial will learn you how to use sockets in PHP Sockets can be used to open connections to other people's computer, or to accept incomming connections on your own computer. There are two ways to open a socket, using the socket_ functions and using the fsockopen() function. With the fsockopen function, you can't listen for connections you can only connect to other people's computer. Creating a Socket You need to create a socket using the socket_create() function. The syntax of the socket_create() function is

$socket = socket_create(domain,type,protocol);

A example of this code in use is

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

The first parameter is the domain, there are two types of domains AF_INET IPv4 internet based protocols, TCP and UDP are common protocols of this protocol family. AF_UNIX Local communication protocol family You will be working with the AF_INET domain, as this is the internet based domain. The second parameter is SOCK_STREAM, this can read and write to the socket. The last parameter is the protocol, SOL_TCP is a TCP protocol. Connecting to a Socket You need to connect to a socket using the socket_connect() function. The syntax of this code is

$socketconnect = socket_connect(socketvariablename, address,port);

A example of this code in use is $socketconnect = socket_connect($socket,'URL',6777); The socket we made is called socket, and we assign this variable socketconnect to the variable socket. Reading a Socket We will now read a socket using the socket_read() function, the syntax for the socket_read() function is

$socketread = socket_read(socketname,length,type);

A example of this code in use is

$socketread = socket_read($socket,2444,PHP_NORMAL_READ);

PHP_NORMAL_READ is a way to read the socket Writing to a socket You can write to a socket using the socket_write() function, the syntax for the socket_write() function is

socket_write(socketname,string,length);

A example of this code in use is

socket_write($socket,"Test",6800);

Thank you for reading my PHP Sockets tutorial Thank you Michael

Description:
This tutorial will learn you how to use sockets in PHP

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options