gpt4 book ai didi

java - Java上的Socket连接,指定IP

转载 作者:行者123 更新时间:2023-12-01 13:41:01 28 4
gpt4 key购买 nike

我正在开发一个程序,其中多个客户端需要与远程服务器交互。
我已经在本地测试过了,一切正常(稍后会详细介绍),但我不明白如何设置远程 IP。
我阅读了 Socket 的 API 和 InetAddress 的 API。这是正确的做法吗? Java如何处理IP?不仅仅是像本地主机那样的简单字符串,对吗?
这是我的代码:

客户:

public class Client {

final String HOST = "localhost";
final int PORT = 5000;
Socket sc;
DataOutputStream message;
DataInputStream istream;

public void initClient() {
try {
sc = new Socket(HOST, PORT);
message = new DataOutputStream(sc.getOutputStream());
message.writeUTF("test");
sc.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}

服务器:

public class Server {

final int PORT = 5000;
ServerSocket sc;
Socket so;
DataOutputStream ostream;
String incomingMessage;

public void initServer() {
try {
sc = new ServerSocket(PORT);
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
}

BufferedReader input;

while(true){
try {
so = new Socket();
System.out.println("Waiting for clients...");
so = sc.accept();
System.out.println("A client has connected.");

input = new BufferedReader(new InputStreamReader(so.getInputStream()));
ostream = new DataOutputStream(so.getOutputStream());
System.out.println("Confirming connection...");
ostream.writeUTF("Successful connection.");

incomingMessage = input.readLine();
System.out.println(incomingMessage);
sc.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}

此外,我在本地测试中遇到了一些麻烦。
首先,有时我会得到以下结果:

等待客户...
客户端已连接。
正在确认连接...
错误:软件导致连接中止:接收失败

虽然其他时候它工作得很好。好吧,至少是第一个连接。

最后一个问题:
当我尝试从服务器向客户端发送消息时,程序进入无限循环,需要手动关闭。我将其添加到代码中来执行此操作:

fromServerToClient = new BufferedReader(new InputStreamReader(sc.getInputStream()));  
text = fromServerToClient.readLine();
System.out.println(text);

我做得对吗?

谢谢。

最佳答案

而不是使用

String host = "localhost";

你可以使用类似的东西

String host = "www.ibm.com";

String host = "8.8.8.8";

关于java - Java上的Socket连接,指定IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20776988/

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