【问题标题】:simple client server communication between java and phpjava和php之间的简单客户端服务器通信
【发布时间】:2012-12-16 14:28:20
【问题描述】:

我需要从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);
?>

【问题讨论】:

    标签: java php sockets


    【解决方案1】:

    知道了!,

    我们需要添加$message = "Apple\n"; 而不是$message = 'Apple\n';

    【讨论】:

      【解决方案2】:

      尝试在您的消息中添加行尾。

      $message = 'Apple\n';
      

      readLine 将始终等待行尾。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-10
        相关资源
        最近更新 更多