Java如何使服务器允许连接到套接字端口?

Posted borter

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java如何使服务器允许连接到套接字端口?相关的知识,希望对你有一定的参考价值。

在Java编程中,如何使服务器允许连接到套接字端口?

以下示例显示如何使服务器通过使用ServerSocket类的server.accept()方法和Socket类的sock.getInetAddress()方法来允许连接到套接字端口:`1234

package com.yiibai;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ConnectingSocket {
    public static void main(String[] args) {
      try {
         ServerSocket server = new ServerSocket(12345);
         while (true) {
            System.out.println("Listening");
            Socket sock = server.accept();
            InetAddress addr = sock.getInetAddress();
            System.out.println("Connection made to " + addr.getHostName() + " (" + addr.getHostAddress() + ")");
            pause(5000);
            sock.close();
         }
      } catch (IOException e) {
         System.out.println("Exception detected: " + e);
      }
   }

    private static void pause(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
        }
    }
}
Java

上述代码示例将产生以下结果 -

Listening
Connection made to 127.0.0.1 (127.0.0.1)
Listening
Shell

客户端代码参考如下 -

package com.yiibai;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class SocketClient {
    public static void main(String[] args) {
        try {
            //InetAddress addr = InetAddress.getByName("127.0.0.1");
            Socket theSocket = new Socket("127.0.0.1", 12345);
            System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort()
                    + " from port " + theSocket.getLocalPort() + " of " + theSocket.getLocalAddress());
        } catch (UnknownHostException e) {
            System.err.println("I can‘t find " + e);
        } catch (SocketException e) {
            System.err.println("Could not connect to " + e);
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

以上是关于Java如何使服务器允许连接到套接字端口?的主要内容,如果未能解决你的问题,请参考以下文章

无法连接到 WebSocket 服务器。不知道为啥

Java如何在指定端口创建套接字?

如何查看所有连接到HTTP或HTTPS端口的客户端

Python套接字通过端口转发连接到服务器

如何从网络服务器检查套接字?

XAMPP apache 无法连接到监听端口