• 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);
            }
        }
    }
  • 相关阅读:
    使用Spring的ReloadableResourceBundleMessageSource读取properties配置
    IFrame自适应高度
    Js返回页面顶部
    复制页面内容时添加额外信息
    怎样将Excel中的日期格式转换为文本格式
    为Tomcat页面设置访问权限(HTTP)
    为tomcat页面设置访问权限(BASIC认证)
    离线安装Maven FOR Eclipse插件
    sharepoint 获得上级和部门的封装函数
    SharePoint定制开发个性皮肤
  • 原文地址:https://www.cnblogs.com/borter/p/9617169.html
Copyright © 2020-2023  润新知