java php communication



我编写了一个客户端java应用程序,它通过http与php服务器通信。我需要在java(客户端)端实现一个监听器来响应php服务器发出的请求。目前,java应用程序正在服务器上点击一个每分钟更新一次的文本文件。

这还可以,但现在客户端java应用程序的数量正在增加,这个原始系统开始崩溃。

改变这种状况的最佳方法是什么?我在java客户端应用程序上尝试了一个javaServerSocket侦听器,但无法实现。我很难完成沟通。web上的所有示例都使用localhost作为ip地址示例,我的php服务器是远程托管的。

我是否需要获取客户端机器的ip地址并将其发送到php服务器,以便php知道将消息发送到哪里?这是java代码。。。网上到处都是。。。

public class MyJavaServer
{
    public static void main(String[] args)
    {

        int port = 4444;
        ServerSocket listenSock = null; //the listening server socket
        Socket sock = null;          //the socket that will actually be used for communication
        try
        {
            System.out.println("listen");
            listenSock = new ServerSocket(port);
            while (true)
            {
                sock = listenSock.accept(); 
                BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
                String line = "";
                while ((line = br.readLine()) != null)
                {
                    bw.write("PHP said: " + line + "n");
                    bw.flush();
                }
                //Closing streams and the current socket (not the listening socket!)
                bw.close();
                br.close();
                sock.close();
            }
        }
        catch (IOException ex)
        {
            System.out.println(ex);
        }
    }
}

这是php

$PORT = 4444; //the port on which we are connecting to the "remote" machine
$HOST = "ip address(not sure here)"; //the ip of the remote machine(of the client java app's computer???
$sock = socket_create(AF_INET, SOCK_STREAM, 0) 
        or die("error: could not create socketn");
$succ = socket_connect($sock, $HOST, $PORT) 
        or die("error: could not connect to hostn");
$text = "Hello, Java!n"; //the text we want to send to the server
socket_write($sock, $text . "n", strlen($text) + 1) 
        or die("error: failed to write to socketn");
$reply = socket_read($sock, 10000, PHP_NORMAL_READ)
        or die("error: failed to read from socketn");
echo $reply;

这根本不起作用。java应用程序侦听,但php脚本从不连接。

此外,这是满足我需求的最佳方法吗??谢谢

如果php服务器机器可以连接到java客户端机器,那么包含的代码就可以工作。在您的情况下,这是在整个web上,这意味着java客户端机器应该有一个可供公众访问的IP。一旦您拥有了它,将该IP分配给$HOST,那么代码就会正常运行。

假设没有一个客户端可以拥有公共IP,我认为最好的方法是让您的java客户端使用HTTP请求以请求-回复的方式与您的PHP服务器进行通信。java客户端就像web浏览器一样,发送HTTP请求并接收包含java客户端所需数据的HTTP回复。当客户端数量上升到PHP服务器无法处理的程度时,您可以扩大规模。虽然我自己还没有这种经验,但现在扩展PHP服务器并不罕见。

最新更新