java - 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();
}
}
我尝试了很多不同的组合和解决方案,但找不到任何以前做过的例子。我想知道我做错了什么,这样我才能摆脱这种头痛。提前致谢!
解决方案
Java Socket 和 ServerSocket 使用 TPC,Heroku 不免费支持。结果,服务器将运行良好,但是通过 TCP 发送的任何内容(包括连接尝试)都不会到达您的服务器,除非它们是通过 http 完成的。
推荐阅读
- react-native - React Native - 重定向到“主页”后显示启动画面
- android - Android VpnService 不允许自己
- r - 如何从原始数据集中计算样本数据集?
- python - 以节省内存的方式将加权边列表转换为邻接矩阵
- travis-ci - 电子邮件验证错误和未触发自动构建
- c# - Json 使用动态属性名称反序列化对象数组
- c++ - 找到您正在考虑的数字的程序无法正常运行,出了什么问题?
- javascript - V8 c++ - 无法反序列化 V8 快照 blob
- javascript - 如何使用jquery预填充字段
- django - 使用 Django 上传一个大的 csv 文件(100MB)需要多长时间?