2013-05-15 28 views
5

我最近訪問了heroku.com網站,並嘗試在那裏部署我的第一個java程序,實際上我有一個很好的開始使用他們的java部署教程,並讓它運行正常。現在我有一個服務器代碼,我需要在那裏部署,我試圖按照這個例子,但我有一些問題,例如,部署簡單的服務器代碼到Heroku

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在他們的網站上傳我的服務器代碼是否還有其他我需要做的事情?

在此先感謝

回答

5

在Heroku上,應用程序必須bind to the HTTP port provided in the $PORT environment variable。鑑於此,上述應用程序代碼中的兩個主要問題是:1)您綁定到硬編碼端口(6780); 2)您的應用程序使用TCP而不是HTTP。正如tutorial所示,使用這樣的碼頭,以實現應用程序的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(); 
    } 
} 
+0

確定,但將在客戶端代碼中這是一個正常的HTTP連接案件?!這實際上是一個非常簡單的例子,我真正在做的是構建多人遊戲,客戶端可以連接到服務器並進行遊戲,因此,在您更改服務器代碼之後,我對您的客戶端代碼感興趣。請記住,我打算擴展代碼以支持多人遊戲,因此我們將不勝感激 –

+0

是的,您的客戶也需要使用HTTP。 Heroku應用程序可以實現出站TCP連接(例如到數據庫),但所有入站連接都需要通過HTTP。有關更多詳細信息,請參閱[有關Heroku HTTP路由的信息](https://devcenter.heroku.com/articles/http-routing)。 – ryanbrainard