gpt4 book ai didi

公共(public)IP的java客户端服务器程序

转载 作者:行者123 更新时间:2023-11-29 04:45:19 25 4
gpt4 key购买 nike

我用java写了一个客户端服务器通信的普通程序。它在本地主机和专用网络上运行良好。现在我想让程序与连接到互联网的其他地方的远程机器通信。这是我的代码。

客户端代码

public class GreetingClient
{
public static void main(String [] args)
{
String serverName = "27.123.66.43";
int port = Integer.parseInt("5005");
try
{
System.out.println("Connecting to " + serverName +
" on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

服务器代码

import java.net.*;
import java.io.*;

public class GreetingServer extends Thread {
private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
//serverSocket.setSoTimeout(10000);
}

public void run() {
while (true) {
try {
System.out.println("Waiting for client on port "
+ serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in
= new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out
= new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}

public static void main(String[] args) {
int port = Integer.parseInt("5005");
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}

服务器的公共(public) IP 为 27.123.66.43。该程序不适用于公共(public) ip。如何将此程序用于公共(public) ip?

最佳答案

由于它在您的本地专用网络上运行,我认为您可能需要检查您的远程服务器上的端口 5005 是否允许从您的客户端服务器访问。您可以通过执行以下命令进行测试:

# I assume your remote server is a *nix server, here you can use nc to create a TCP server
nc -l 27.123.66.43 5005

# use telnet to connect to your remote server on your client server
telnet 27.123.66.43 5005

关于公共(public)IP的java客户端服务器程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37424342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com