【问题标题】:Java chat program works on localhost, but not when hosting on HerokuJava 聊天程序在本地主机上工作,但在 Heroku 上托管时不能
【发布时间】:2021-12-13 03:41:31
【问题描述】:

长话短说,我从 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();

}
}

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

【问题讨论】:

  • 您使用"&lt;my app name&gt;.herokuapp.com" 进行连接,您是隐藏了您的应用名称还是无意?这可能是问题所在。
  • 我隐藏了名字。

标签: java heroku serversocket


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多