Java和PHP之间的简单客户端服务器通信

9

我可以帮您翻译成中文。以下是需要翻译的内容:

我需要从php客户端向java服务器发送信息,但尽管服务器上成功执行了一个打印语句,但无法在服务器端接收来自客户端的文本。以下是代码:

Java服务器:


代码如下:
import java.io.BufferedReader;
import java.net.*;
import java.io.*;

public class javaphp2 {
    private static ServerSocket socket;

    private static Socket connection;
    private static String command       = new String();
    private static String responseStr   = new String();

    private static int port = 4309;

    public static void main(String args[])  {
        System.out.println("Signal Server is running.");

        try  {
            socket = new ServerSocket(port);

            while (true)  {
                connection = socket.accept();

                InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
                DataOutputStream response = new DataOutputStream(connection.getOutputStream());
                BufferedReader input = new BufferedReader(inputStream);

                command = input.readLine();
                //System.out.println("The input is" + command);
                response.writeBytes(responseStr);
                response.flush();
                //response.close();

                System.out.println("Running");
            }
        } catch (IOException e)  {
            System.out.println("Fail!: " + e.toString());
        }

        System.out.println("Closing...");
    }
}

PHP客户端:

#!/usr/local/bin/php -q
<?php
$address = '132.119.90.165';
$port = 4309;

$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_connect($socket, $address, $port);

$message = 'Apple';
$len = strlen($message);

$status = socket_sendto($socket, $message, $len, 0, $address, $port);
if($status !== FALSE)
{
    $message = '';
    $next = '';
    while ($next = socket_read($socket, 4096))
    {
        $message .= $next;
    }

    echo $message;
}
else
{
    echo "Failed";
}

socket_close($socket);
?>
2个回答

8

明白了!

我们需要将$message = 'Apple\n';改为$message = "Apple\n";


0
尝试在您的消息中添加一个行尾。
$message = 'Apple\n';

readLine会一直等待行末结束。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接