Simple Client-Server socket program in PHP

Introduction

Sockets are used for interprocess communication. Interprocess communication is generally based on client-server model. In this case, client-server are the applications that interact with each other.

Interaction between client and server requires a connection. Socket programming is responsible for establishing that connection between applications to interact.

By the end of this tip, we will learn how to create a simple client-server in PHP. We will also learn how client application sends message to server and receives it from the same.

Using the Code

Aim: Develop a client to send a string message to server and server to return reverse of the same message to client.

PHP SERVER:

Step 1: Set variables such as "host" and "port"

$host = "127.0.0.1";

$port = 5353

// No timeout

set_time_limit(0);

Port number can be any positive integer between 1024 - 65535

Step 2: Create Socket

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");

Step 3: Bind the socket to port and host

Here the created socket resource is bound to IP address and port number.

$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");

Step 4: Start listening to the socket

$result = socket_listen($socket, 3) or die("Could not sest up socket listener\n");

Step 5: Accept incoming connection

This function accepts incoming connection request on the created socket. After accepting the connection from client socket, this function returns another socket resource that is actually responsible

for communication with the corresponding client socket. Here "$spawn" is that socket resource which is responsible for communication with client socket.

$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");

So far, we have prepared our server socket but the script doesn't actually do anything. Keeping to our aforesaid aim, we will read message from client socket and then send back reverse message to

the client socket again.

Step 6: Read the message from the Client socket

$input = socket_read($spawn, 1024) or die("Could not read input\n");

Step 7: Reverse the message

$output = strrev($input) . "\n";

Step 8: Send message to the client socket

socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");

Close the socket

socket_close($spawn);

socket_close($socket);

This completes with the server. Now we will learn to create PHP client.

PHP CLIENT

The first two steps are the same in ther server.

Step 1: Set variables such as "host" and "port"

$host = "127.0.0.1";

$port = 5353;

// No Timeout

set_time_limit(0);

Note: Here the port and host should same as defined in server.

Step2 : Create Socket

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");

Step 3: Connect to the server

$result = socket_connect($socket, $host, $port) or die("Could not connect to server");

Here unlike server, client socket is not bound with port and host. Instead it connects to server socket, waiting to accept the connection from client socket. Connection of client to server socket is established in this step.

Step 4: Write to server socket

socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");

Step 5: Read the response from the server

$result = socket_read($socket, 1024) or die("Could not read server response\n");

echo "Reply From Server:" . $result;

Step 6: Close the socket

socket_close($socket);

[PHP-Socket] Socket Programming in PHP的更多相关文章

  1. Python socket – network programming tutorial

    原文:https://www.binarytides.com/python-socket-programming-tutorial/ --------------------------------- ...

  2. [Socket]Socket文件传输

    1.Server import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException ...

  3. [Socket]Socket聊天小程序

    一个简单是Socket聊天小程序,读写操作在不同的线程中.服务器端采用线程池. 1.Server import java.io.IOException; import java.net.ServerS ...

  4. [Socket]Socket进程间的通信

    转自:http://blog.csdn.net/giantpoplar/article/details/47657303 前面说到的进程间的通信,所通信的进程都是在同一台计算机上的,而使用socket ...

  5. ResourceWarning: unclosed <socket.socket fd=864, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('10.100.x.x', 37321), raddr=('10.1.x.x', 8500)>解决办法

    将代码封装,并使用unittest调用时,返回如下警告: C:\python3.6\lib\collections\__init__.py:431: ResourceWarning: unclosed ...

  6. socket socket讲解

    socket  socket讲解 一.socket是何物? 参考百度百科: http://baike.baidu.com/link?url=4YNURsJLEaL0II79C68gPUoYKliXWJ ...

  7. Python socket & socket server

    socket 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket(套接字). 建立网络通信连接至少要一对socket.socket是对TCP/IP的封装 使用方法 ...

  8. dotnet调用node.js写的socket服务(websocket/socket/socket.io)

    https://github.com/jstott/socketio4net/tree/develop socket.io服务端node.js,.里面有js写的客户端:http://socket.io ...

  9. socket系列之客户端socket——Socket类

    假设TCP套接字服务器端已经建立好并正在监听客户端的连接了,那么客户端就可以通过Socket类来发起连接.客户端发起一个连接请求后,就被动地在等待服务器的响应.这个类同样位于java.net包中,包含 ...

  10. 执行Socket socket = new Socket(ip, port);时抛出个异常:android.os.NetworkOnMainThreadException解决办法

    首先,确认你的android版本是4.0之后再用此方法解决,因为在4.0之后在主线程里面执行Http请求才会报这个错,也许是怕Http请求时间太长造成程序假死的情况吧.Android在4.0之前的版本 ...

随机推荐

  1. java学习第四天

    那些逻辑语言就基本了解下,今天想到了一个问题就是关于for和while的区别,从专业上来说,for和while基本上是相同的,但是for是只允许一次访问的,如果结束后就无法继续访问,而while则可以 ...

  2. web项目启动报错Unknown character set: 'utf8mb4' in mysql

    网上一查,有的说是mysql驱动的问题,有的说创建数据库的时候指定utf8编码,换了各种mysql版本,最后换了5.1.6版本的mysql驱动后成功启动!问题解决!OMG

  3. Attribute "resource" must be declared for element type "mapper".

    今天在玩mybatis的时候,遇到这个奇葩问题. 最后发现,原因是 dtd文件配置错误了.错把Mapper的直接copy过来 把DOCTYPE mapper改成configuration,Mapper ...

  4. 问题Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found解决方法

    问题Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not fo ...

  5. bind的用处

    刚做的项目,遇到过这样的问题,就是在动态追加标签时,给追加的标签添加事件时,在标签内追加不了,后来使用了delegate代理,能响应了,但也是不能给动态追加的代理 $("body" ...

  6. 解决IE上登陆oracle OEM时报:“证书错误,导航已阻止”的错误

    今天在IE上登陆OEM时,报证书错误,导航已阻止,我选择:继续浏览此网站(不推荐),但是点了之后还没有反应,在网上搜了很多,原因基本都是windows的问题,最后发现问题是:oracle oem证书的 ...

  7. POJ 1113 - Wall 凸包

    此题为凸包问题模板题,题目中所给点均为整点,考虑到数据范围问题求norm()时先转换成double了,把norm()那句改成<vector>压栈即可求得凸包. 初次提交被坑得很惨,在GDB ...

  8. LeetCode OJ 331. Verify Preorder Serialization of a Binary Tree

    One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, ...

  9. Python全栈--7.3--模块补充configparser--logging--subprocess--os.system--shutil

    模块补充: 一.configparser用于处理特定格式的文件,其本质是利用open来操作文件 继承到2版本 configparser 实现了更多智能特征,更有壳预见性,新的应用更偏好这个版本, 处理 ...

  10. docker 安装

    Docker使用了一种叫AUFS的文件系统,这种文件系统可以让你一层一层地叠加修改你的文件,最底下的文件系统是只读的,如果需要修改文件,AUFS会增加一个可写的层(Layer),这样有很多好处,例如不 ...