Home php教程 PHP开发 PHP Socket communication UDP communication example

PHP Socket communication UDP communication example

Dec 22, 2016 am 09:46 AM
socket communication

The example in this article describes the UDP communication method of PHP's Socket communication. Share it with everyone for your reference. The details are as follows:

1. Create a simple UDP server

//服务器信息
$server = 'udp://127.0.0.1:9998';
//消息结束符号
$msg_eof = "\n";
$socket = stream_socket_server($server, $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
  die("$errstr ($errno)");
}
do {
  //接收客户端发来的信息
  $inMsg = stream_socket_recvfrom($socket, 1024, 0, $peer);
  //服务端打印出相关信息
  echo "Client : $peer\n";
  echo "Receive : {$inMsg}";
  //给客户端发送信息
  $outMsg = substr($inMsg, 0, (strrpos($inMsg, $msg_eof))).' -- '.date("D M j H:i:s Y\r\n");
  stream_socket_sendto($socket, $outMsg, 0, $peer);
} while ($inMsg !== false);
Copy after login

2. A simple client

function udpGet($sendMsg = '', $ip = '127.0.0.1', $port = '9998'){
  $handle = stream_socket_client("udp://{$ip}:{$port}", $errno, $errstr);
  if( !$handle ){
    die("ERROR: {$errno} - {$errstr}\n");
  }
  fwrite($handle, $sendMsg."\n");
  $result = fread($handle, 1024);
  fclose($handle);
  return $result;
}
$result = udpGet('Hello World');
echo $result;
Copy after login

I hope this article will be helpful to everyone’s PHP programming design.

For more articles related to UDP communication examples of PHP’s Socket communication, please pay attention to the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)