The simple function implemented by
demo is to accept the string written by the PHP end, and then return it to the output end as it is. The code is as follows:
The code is as follows:
import java.io.*; import java.net.*; public class Server { public static void main ( String [] args) throws IO Exception { System.out. print ln("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 the 5678 port. When the message is received, the received message will be returned to the client as it is...
The PHP code is as follows:
The 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);
The PHP program connects to the 5678 port of the local machine, writes Hello, and then reads the returned data...will return Data is output to the browser...
First run the java server, and then use the browser to access the PHP page. You will see the Hello returned from the server
[Related recommendations]
1. Detailed explanation of the valueOf method example in java
2. Share the example code in java that handles sticky packets during socket communication
3. Java instance-ServerSocket and Socket communication instance