我有一个简单的服务器 - 客户端Tic Tac Toe游戏在控制台中运行,我在我的本地主机上成功运行此代码,我现在需要的是在服务器上部署服务器代码,例如Heroku或任何其他托管站点除了我作为主持人,我已经关注了Heroku教程,但仍然无法弄清楚剩下的https://devcenter.heroku.com/articles/java
这是我的服务器代码
public class TCPServer {
public static void main(String argv[]) throws Exception {
// String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(6780);
BufferedReader[] inFromClient = new BufferedReader[2];
Socket[] connectionSocket = new Socket[2];
DataOutputStream[] outToClient = new DataOutputStream[2];
String labels = "XO";
for (int i = 0; i < 2; i++) {
connectionSocket[i] = welcomeSocket.accept();
inFromClient[i] = new BufferedReader(new InputStreamReader(connectionSocket[i].getInputStream()));
outToClient[i] = new DataOutputStream(connectionSocket[i].getOutputStream());
outToClient[i].write(labels.charAt(i));
System.out.println("one is here");
}
int next = 0;
while (true) {
String s = inFromClient[next].readLine();
next ^= 1;
outToClient[next].writeBytes(s + "\n");
}
}
}
这是我的客户代码
class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket(server, port);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
char[][] XO = new char[3][3];
for (char[] arr : XO)
Arrays.fill(arr, '-');
char playerSign = (char) inFromServer.read();
boolean turn = false;
if (playerSign == 'X')
turn = true;
while (true) {
if (turn) {
sentence = inFromUser.readLine();
String[] split = sentence.split(" ");
int a = Integer.parseInt(split[0]);
int b = Integer.parseInt(split[1]);
if (XO[a][b] != '-')
continue;
outToServer.writeBytes(sentence + '\n');
XO[a][b] = playerSign;
turn = false;
} else {
String next = inFromServer.readLine();
String[] split = next.split(" ");
XO[Integer.parseInt(split[0])][Integer.parseInt(split[1])] = playerSign == 'X' ? 'O' : 'X';
turn = true;
}
for (char[] arr : XO)
System.out.println(new String(arr));
}
// clientSocket.close();
}
}
现在我已经尝试将相同的服务器代码放在heroku上,但它不起作用。我确信我遇到了问题,而且我不确定我的客户端应该连接哪个服务器和端口,这件事的任何帮助都将不胜感激
答案 0 :(得分:1)
Heroku首先不支持TCP协议,其次,您必须将服务器绑定到服务为您提供的端口。例如,在node.js中,您使用process.env.PORT
访问它,但我承认我无法通过Java访问此变量。但即使您确实使用了他们提供的端口,也只支持HTTP和HTTPS(如果您通过他们的实验室启用它们,则支持websockets),但他们对TCP没有任何支持。