在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);
}
}
}
Java
上述代码示例将产生以下结果 -
Connected to /112.124.103.85 on port 80 from port 57229 of /192.168.1.50