drp935159 2013-01-14 01:02
浏览 35
已采纳

使PHP服务器读取基于Java的客户端

public class Client {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    Socket sock = new Socket();
    sock.connect(new InetSocketAddress(InetAddress.getLocalHost(), 43594));

    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    DataInputStream in = new DataInputStream(sock.getInputStream());

    out.writeByte(255);
    out.writeLong(133713371337L);

    System.out.println("Response: " + in.readByte() + ", " + in.readLong());

    sock.close();
}

and the PHP server meant to read and write back to the java client:

<?php
require 'Stream.php';
$stream = new Stream();

$address = '127.0.0.1';
$port = 43594;
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, 0, $port) or die('Could not bind to address');
socket_listen($sock);
echo "Server listening on port " . $port . "...";
$client = socket_accept($sock);

$data = socket_read($client, 1, PHP_BINARY_READ);
$byte_array = unpack('C*', $data);
$stream->setStream($byte_array);
$b2 = $stream->readUnsignedByte();

$l1 = socket_read($client, $stream->readQWord());
echo $b1 . " " . $l1;
socket_write($client, 0);
socket_write($client, $stream->writeQWord(2148000000));

The stream class being used: http://pastebin.com/p1vc9aPG

I'm trying to write a client in java that contacts, sends and reads data to/from the server. The server is written in PHP and ran via cli, while the client is written in java. Please help if you can, there probably aren't many people who can help with this issue.

The protocol is already established and I'm just trying to implement it in PHP. I can't seem to read/write back to the java client from the PHP page.

The client side in Java is defined how I want it to be. What I'm looking for is the equivalent server in PHP and I can't seem to get it to work.

  • 写回答

2条回答 默认 最新

  • dououde4065 2013-01-14 01:11
    关注

    I've actually written this the other way around, the client was a PHP web app and the server was a java daemon under jsvc.

    The first consideration should be defining a transfer protocol, since the types and object representations of the two languages are different and they might be running on hardware with different numeric representations. I'd recommend JSON or XML.

    After that your server probably needs to be able to handle multiple connections, so threading or non-blocking socket I/O will be needed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示