2013-01-14 01:02
浏览 34


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());


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


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

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

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

$data = socket_read($client, 1, PHP_BINARY_READ);
$byte_array = unpack('C*', $data);
$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.

    点赞 评论
  • doucong3048 2013-01-14 01:06

    First, you should call .flush() after you write to the socket in your Java code. The data won't get sent to the server otherwise.

    Then, communications between network endpoints is just about agreement on the protocol used. There is nothing language specific here...

    点赞 评论

相关推荐 更多相似问题