码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-09-10 11:16:29      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:toolbar   tcl   ade   bool   vat   read   word   pac   ken   

在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如何使服务器允许连接到套接字端口?

标签:toolbar   tcl   ade   bool   vat   read   word   pac   ken   

原文地址:https://www.cnblogs.com/borter/p/9617169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!