位置:首页 > 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