首页 > 解决方案 > Java 聊天程序在本地主机上工作,但在 Heroku 上托管时不能

问题描述

长话短说,我从 GeeksForGeeks 窃取并修改了一些代码来练习套接字。运行为 localhost 修改的代码在桌面上运行良好,但在修改并尝试在 Heroku 上托管时,我似乎无法在服务器和客户端之间建立连接。服务器似乎在 Heroku 上启动并运行良好,并记录了我什至没有建立的连接(不知道这些连接来自哪里)。另一方面,客户端似乎已连接,但是当我发送消息时什么都不做。服务器甚至没有记录我尝试的连接,所以我知道它可能甚至没有连接。

服务器代码:https ://github.com/RenegadeB5/socket in /src/main/java/

客户代码:

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client
{

public static void main(String args[]) throws UnknownHostException, IOException
{
    Scanner scn = new Scanner(System.in);
    // establish the connection
    Socket s = new Socket("<my app name>.herokuapp.com", 80);
    
    // obtaining input and out streams
    DataInputStream dis = new DataInputStream(s.getInputStream());
    DataOutputStream dos = new DataOutputStream(s.getOutputStream());

    // sendMessage thread
    Thread sendMessage = new Thread(new Runnable()
    {
        @Override
        public void run() {
            while (true) {

                // read the message to deliver.
                String msg = scn.nextLine();
                
                try {
                    // write on the output stream
                    dos.writeUTF(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    
    // readMessage thread
    Thread readMessage = new Thread(new Runnable()
    {
        @Override
        public void run() {

            while (true) {
                try {
                    // read the message sent to this client
                    String msg = dis.readUTF();
                    System.out.println(msg);
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }
    });

    sendMessage.start();
    readMessage.start();

}
}

我尝试了很多不同的组合和解决方案,但找不到任何以前做过的例子。我想知道我做错了什么,这样我才能摆脱这种头痛。提前致谢!

标签: javaherokuserversocket

解决方案


Java Socket 和 ServerSocket 使用 TPC,Heroku 不免费支持。结果,服务器将运行良好,但是通过 TCP 发送的任何内容(包括连接尝试)都不会到达您的服务器,除非它们是通过 http 完成的。


推荐阅读