gpt4 book ai didi

java - 为什么ServerSocket对象的accept方法返回具有不同端口的Socket对象

转载 作者:行者123 更新时间:2023-12-02 06:19:29 24 4
gpt4 key购买 nike

我已经在 stackoverflow 上搜索了我的问题的答案,但我无法从这些线程中得​​到答案。我的问题是为什么 ServeerSocket 对象的 accept() 方法返回一个监听服务器计算机上不同端口的 Socket 对象,而服务器正在监听的端口是另一个端口。

JAVA代码:

package chat.server;

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

public class ServerApp {
public String[] advices = {"Take smaller bites",
"Go for the tight jeans. No they do NOT make you look fat.",
"One word: inappropriate",
"Just for today, be honest. Tell your boss what you *really* think",
"You might want to rethink that haircut."};
public ServerSocket serverSocket;

public ServerApp()
{
try
{
serverSocket = new ServerSocket(4245);
System.out.println("Server Started.");
}catch (Exception exception)
{
exception.printStackTrace();
}
}

public static void main(String[] args) {
ServerApp server = new ServerApp();
while(true)
{
server.sendMessage();
}

}

public void sendMessage()
{
String advice;
try
{
Socket socket = serverSocket.accept();//here comes my question
System.out.println(socket.getPort());
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());

advice = getAdvice();
printWriter.write(advice);

printWriter.close();
System.out.println(advice);
}catch (Exception exception)
{
exception.printStackTrace();
}
}

private String getAdvice() {
int random = (int) (Math.random() * advices.length);
return advices[random];
}
}

服务器从同一个端口号监听并应答客户端,这不是很正常吗?

最佳答案

如果您希望从连接的套接字获取值 4245(您的服务器套接字正在监听的端口),您需要使用 getLocalPort,而不是 getPort

getPort :

Returns the remote port number to which this socket is connected.

getLocalPort :

Returns the local port number to which this socket is bound.

(我的重点)

关于java - 为什么ServerSocket对象的accept方法返回具有不同端口的Socket对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141485/

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