简体   繁体   English

java和php之间的简单客户端服务器通信

[英]simple client server communication between java and php

I need to send information from php client to java server, but none is receiving on server side though one print statement is successfully executed on server, the text from client is not able to receive on the server side. 我需要从php客户端发送信息到java服务器,但是没有一个在服务器端接收,虽然在服务器上成功执行了一个print语句,客户端的文本无法在服务器端接收。 Here are the codes: 以下是代码:

Java Server: 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 Client: 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);
?>

Got it !, 得到它了 !,

We need to add $message = "Apple\\n"; 我们需要添加$message = "Apple\\n"; instead of $message = 'Apple\\n'; 而不是$message = 'Apple\\n';

Try to add a line-end to your message. 尝试在邮件中添加行尾。

$message = 'Apple\n';

readLine will always wait for the line-end. readLine将始终等待行结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM