Java如何在指定埠建立通訊端?

2019-10-16 22:28:12

在Java程式設計中,如何在指定埠建立通訊端並連線到指定伺服器的埠?

下面的例子演示了Socket類的Socket建構函式,並且使用getLocalPort(),getLocalAddress()getInetAddress()以及getPort()方法獲取Socket細節。

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 CreateSocket {
    public static void main(String[] args) {
        try {
            InetAddress addr = InetAddress.getByName("112.124.103.85");
            Socket theSocket = new Socket(addr, 80);
            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);
        }
    }
}

上述程式碼範例將產生以下結果 -

Connected to /112.124.103.85 on port 80 from port 57229 of /192.168.1.50