我写了一个客户端Java应用程序,它通过http与PHP服务器进行通信。我需要在java(客户端)端实现一个监听器来响应php服务器发出的请求。目前,java应用程序正在每分钟更新一次的服务器上创建一个文本文件。
这工作正常,但现在客户端Java应用程序的数量正在上升,这个原始系统开始崩溃。
改变这种情况的最好方法是什么?我在java客户端应用程序上尝试了一个java ServerSocket监听器,但无法使其工作。我无法完成沟通。 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 socket\n");
$succ = socket_connect($sock, $HOST, $PORT)
or die("error: could not connect to host\n");
$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 socket\n");
$reply = socket_read($sock, 10000, PHP_NORMAL_READ)
or die("error: failed to read from socket\n");
echo $reply;这根本行不通。 java应用程序侦听,但php脚本从不连接。
另外,这是我需要的最佳方法吗?
谢谢。