无为清净楼资源网 Design By www.qnjia.com

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

复制代码 代码如下:
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");
              }
        }
}

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

复制代码 代码如下:
<?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程序连接本机的5678端口,写入 Hello,然后读取返回的数据……将返回的数据,输出到浏览器……
先运行起java的服务端,然后用浏览器访问PHP页面,将看到从服务器端返回的Hello

标签:
php,java,通信,socket

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com