我最近访问过heroku.com网站,并尝试在那里部署我的第一个java程序,我实际上有一个良好的开端使用他们的Java部署教程,并让它运行正常。现在我有一个我需要在那里部署的服务器代码,我试着按照这个例子,但我有一些问题,如,
1-在这种情况下主机是什么,我已经尝试了应用程序链接,就好像它是主机但是它会抛出错误,
这是我的示例服务器代码
public class DateServer {
/** Runs the server. */
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(6780);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
这是我的客户代码
public class DateClient {
/** Runs the client as an application. First it displays a dialog box asking for the IP address or hostname of a host running the date server, then connects to it and displays the date that it serves. */
public static void main(String[] args) throws IOException {
//I used my serverAddress is my external ip address
Socket s = new Socket(serverAddress, 6780);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
我在他们的网站上按照本教程https://devcenter.heroku.com/articles/java上传我的服务器代码我还需要做些什么吗?
提前致谢
答案 0 :(得分:6)
在Heroku上,您的应用程序必须bind to the HTTP port provided in the $PORT environment variable。鉴于此,上面的应用程序代码中的两个主要问题是1)您绑定到硬编码端口(6780
)和2)您的应用程序使用TCP而不是HTTP。如tutorial所示,使用类似Jetty的东西来完成应用程序的HTTP等价物并使用System.getenv("PORT")
绑定到正确的端口,如下所示:
import java.util.Date;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.*;
public class HelloWorld extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print(new Date().toString());
}
public static void main(String[] args) throws Exception{
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(new HelloWorld()),"/*");
server.start();
server.join();
}
}