Java套接字 - 客户端和服务器IP地址

问题描述 投票:1回答:1

我正在编写一个程序,在客户端和服务器之间使用TCP套接字连接。当服务器启动时,我想显示客户端需要用来连接的IP和端口,当客户端连接时,我希望服务器显示客户端连接的IP。我很困惑我应该对每个命令使用哪个命令:

getInetAdress()

getLocalAdress()

getRemoteSocketAdress()

编辑

我之前使用int port = 1234String IP = "localhost"进行测试并且它有效,但我只在一台PC上使用它,所以我认为如果我在不同的计算机上启动服务器和客户端,localhost将无法工作。

这是服务器端:

int port = 1234;

...

public void start() {
        keepRunning = true;
        // create socket
        try {
            ServerSocket server = new ServerSocket(port);
            while (keepRunning) {
                display("Waiting for client connections on "
                        + server.getInetAddress().getLocalHost()
                                .getHostAddress() + ":" + port);
                Socket conn = server.accept();
                if (!keepRunning)
                    break;

                ClientThread t = new ClientThread(conn);
                cList.add(t);
                t.start();

这是客户:

int port = 1234;
String IP = "localhost";
//these variables can be changed from Client GUI before making connection

...


public boolean start() {
    try {
        socket = new Socket(IP, port);
    } catch (Exception e) {
        display("Error connectiong to server:" + e);
        return false;
    }
    try {
        sInput = new ObjectInputStream(socket.getInputStream());
        sOutput = new ObjectOutputStream(socket.getOutputStream());
    } catch (IOException e) {
        display("Exception creating new Input/output Streams: " + e);
        return false;
    }

当我启动服务器时,

display("Waiting for client connections on " + server.getInetAddress().getLocalHost().getHostAddress() + ":" + port);

归还这个:

Waiting for client connections on 192.168.1.104:1234

这是我想要的,但我还是不能让它向我展示这个端口。 1234是我使用的固定值,但我想使用ServerSocket server = new ServerSocket(0);动态地设置端口,然后当我启动客户端时,我只是输入我从服务器获得的值并连接。

我试图在服务器的server.getLocalPort()行使用display,它返回55410或类似的东西,但是当我把这个端口放在客户端进行连接时,它不起作用。我从客户那里得到了Error connectiong to server:java.net.ConnectException: Connection refused: connect.

java sockets
1个回答
0
投票

要获取ServerSocket正在侦听的当前端口,请使用getLocalPort();

http://download.java.net/jdk7/archive/b123/docs/api/java/net/ServerSocket.html#getLocalPort%28%29

getLocalPort

public int getLocalPort()

Returns the port number on which this socket is listening.

If the socket was bound prior to being closed, then this method will continue to return the port number after the socket is closed.

编辑:刚看到你的编辑。您是否尝试通过显式引用IP和端口进行连接?如果是这样,并且它仍然失败,您的服务器计算机可能正在运行防火墙。我先检查一下。

© www.soinside.com 2019 - 2024. All rights reserved.