Home > php教程 > PHP开发 > Implementation code for communication between php and java through socket

Implementation code for communication between php and java through socket

高洛峰
Release: 2016-12-22 09:54:45
Original
1289 people have browsed it

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"); 
              } 
        } 
}
Copy after login

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 ( &#39;could not create socket&#39; ); 
    $connect = socket_connect ( $socket, &#39;127.0.0.1&#39;, 5678 ); 
    //向服务端发送数据 
    socket_write ( $socket, &#39;Hello&#39; . "\n" ); 
    //接受服务端返回数据 
    $str = socket_read ( $socket, 1024, PHP_NORMAL_READ ); 

    echo $str; 
    //关闭 
    socket_close($socket);
Copy after login

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!

Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template