The simple function implemented by the demo is to accept the string written by the PHP side and then return it to the output side as it is. The code is as follows:
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) throws IOException{ System.out.println("Server started !\n"); ServerSocket server=new ServerSocket(5678); while (true){ Socket client=server.accept(); System.out.println("client coming!\n"); PrintWriter printer = new PrintWriter(client.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream())); String m = reader.readLine(); System.out.println("get infomation " + m + "\n from " + client.getInetAddress().toString()); printer.println(m); printer.flush(); printer.close(); printer.close(); client.close(); System.out.println("client leaving!\n"); } } }
After running, the java program will listen to port 5678. After receiving the message, it will return the received message to the client as it is...
The PHP code is as follows:
<?php $socket = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP ) or die ( 'could not create socket' ); $connect = socket_connect ( $socket, '127.0.0.1', 5678 ); //向服务端发送数据 socket_write ( $socket, 'Hello' . "\n" ); //接受服务端返回数据 $str = socket_read ( $socket, 1024, PHP_NORMAL_READ ); echo $str; //关闭 socket_close($socket);
PHP program connects to the local machine Port 5678, write Hello, and then read the returned data...Output the returned data to the browser...
First run the java server, and then use the browser to access the PHP page, you will see the return from the server Hello
For more articles related to the implementation code of PHP and Java communicating through socket, please pay attention to the PHP Chinese website!