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

时间:2014-05-11 11:50:03

标签: java sockets

我正在编写一个程序,在客户端和服务器之间使用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.

1 个答案:

答案 0 :(得分: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和端口进行连接?如果是这样,并且它仍然失败,您的服务器计算机可能正在运行防火墙。我先检查一下。