Home>Article>Java> java与php通过socket通信的实例教程

java与php通过socket通信的实例教程

PHP中文网
PHP中文网 Original
2017-05-27 09:38:26 2160browse

demo实现的简单功能是,接受PHP端写入的字符串,然后原样返回给输出端。代码如下:

代码如下:

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

运行起来,以后该java程序将监听5678端口,当接收到消息以后,将接收的消息原样返回给客户端……
PHP的代码如下:

代码如下:


      

PHP程序连接本机的5678端口,写入 Hello,然后读取返回的数据……将返回的数据,输出到浏览器……
先运行起java的服务端,然后用浏览器访问PHP页面,将看到从服务器端返回的Hello

【相关推荐】

1.详解java 中valueOf方法实例

2.分享java中处理socket通信过程中粘包情况的实例代码

3.Java 实例 - ServerSocket 和 Socket 通信实例

Statement:
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