位置:首頁 > Java技術 > java實例教學 > Java創建Socket

Java創建Socket

如何在特定的端口創建socket?

解決方法

下麵的示例演示如何使用Socket類的Socket構造方法。並使用getLocalPort(),getLocalAddress,getInetAddress()和 getPort()方法也得到套接字的細節。

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

public class Main {
   public static void main(String[] args) {
      try {
         InetAddress addr = 
         InetAddress.getByName("121.125.67.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 /121.125.67.85 on port 80 from port 
2857 of /192.168.1.4