Home  >  Article  >  Backend Development  >  How to use php cocket

How to use php cocket

不言
不言Original
2018-07-05 15:24:161330browse

This article mainly introduces how to use php cocket, which has certain reference value. Now I share it with everyone. Friends in need can refer to it.

Open the command window under window and run the following respectively. Two lines of command:

# php.exe e:/wwwroot/server.php


# php.exe e:/wwwroot/server.php

The following code comes from the official php manual

server.php:

<?php
 //The Server
 error_reporting(E_ALL);
 $address = "127.0.0.1";
 $port = "10000";
  
 
/* create a socket in the AF_INET family, using SOCK_STREAM for TCP connection */
 $mysock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
 
socket_bind($mysock, $address, $port);
 
socket_listen($mysock, 5);
 
$client = socket_accept($mysock);
 
echo "Server started, accepting connections...\n";
  
 
$i = 0;
 while (true == true)
 {
     $i++;
     echo "Sending $i to client.\n";
     socket_write($client, $i, strlen($i));
     
    $input = socket_read($client, 2048);
     echo "Response from client is: $input\n";
     sleep(5);
 }
 
echo "Closing sockets...";
 socket_close($client);
 
socket_close($mysock);

client.php

<?php
 //The Client
 error_reporting(E_ALL);
 
$address = "127.0.0.1";
 $port = 10000;
 
/* Create a TCP/IP socket. */
 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
 if ($socket === false) {
     echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
 } else {
     echo "socket successfully created.\n";
 }
 
echo "Attempting to connect to &#39;$address&#39; on port &#39;$port&#39;...";
 $result = socket_connect($socket, $address, $port);
 if ($result === false) {
     echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
 } else {
     echo "successfully connected to $address.\n";
 }
 
$i = 0;
 while (true == true)
 {
     $i++;
     echo "Sending $i to server.\n";
     socket_write($socket, $i, strlen($i));
     
    $input = socket_read($socket, 2048);
     echo "Response from server is: $input\n";
     sleep(5);
 }
 
echo "Closing socket...";
 socket_close($socket);

The above is this article The entire content, I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

PHP source code php-beast encryption

yii2 GridView::widget used in template twig

The above is the detailed content of How to use php cocket. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn