gpt4 book ai didi

java - 将 Java Applet 连接到 MySQL DB - 通信链路故障

转载 作者:行者123 更新时间:2023-11-29 04:30:29 25 4
gpt4 key购买 nike

我正在尝试将我的 Java Applet 连接到 MySQL 数据库。我知道它有效,因为我可以在本地主机上连接到它并且它可以很好地检索记录列表。但是当我把它放到互联网上时,它不起作用。

这是我的小程序:http://mystikrpg.com/play

它已签名,但我不断收到以下异常:

SQLException Get Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

这怎么会发生,我该怎么做才能解决这个问题?

这是小程序源代码:http://sodan.pastebin.com/jWKTgBSU

最佳答案

开始,下面的异常

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:   Communications link failure

can have the following causes:

  1. IP address or hostname in JDBC URL is wrong.
  2. Hostname in JDBC URL is not recognized by local DNS server.
  3. Port number is missing or wrong in JDBC URL.
  4. DB server is down.
  5. DB server doesn't accept TCP/IP connections.
  6. DB server has run out of connections.
  7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.

Further, do you realize that an Java Applet physically runs at the client machine? I.e. the machine where the webbrowser runs. The client basically downloads the applet from the webserver and it get executed at client (local) machine. The JDBC connection string jdbc:mysql://localhost:3306 would try to connect to a MySQL database running at the very same machine as where the applet runs. You can't reasonably expect that every client on the world will run a MySQL DB, let alone with your database/table.

If all you want is to access the MySQL server hosted at the server machine (there where the webserver runs) and you want to let the applet communicate with it, then you really have to create and run a webservice at the webserver. Since you tagged this question with [PHP] as well, I guess that you're using PHP at the server side, in that case, just create a PHP script which executes the MySQL action accordingly based on the request parameters or pathinfo and returns the MySQL results as for example a JSON or XML string. In the Applet, you can use the Java SE builtin java.net.URLConnection or the more convenienced Apache HttpComponents Client to communicate with the webserver. E.g.

URLconnection connection = new URL(getCodeBase(), "script.php?action=getdetails&productid=1").openConnection();
InputStream response = connection.getInputStream();
// ...

在 Java 中,您可以使用 Google Gson 处理任何 JSON 响应使用 JAXP 的任何 XML 响应。


也就是说(与当前问题无关),您正在使用的 JDBC 驱动程序名称是已弃用 org.gjt.mm.mysql。驱动程序。我强烈建议使用十多年前引入的正确驱动程序名称来替换旧的驱动程序名称:com.mysql.jdbc.Driver。此外,也不需要 Class#forName() 之后的 Class#newInstance() 调用。这是为了解决旧驱动程序中的一个错误。另见 this explanation .

关于java - 将 Java Applet 连接到 MySQL DB - 通信链路故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3192172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com