Java网络工具类

来源:互联网 发布:mysql if else 编辑:程序博客网 时间:2024/05/21 06:54

Java网络工具类

1、NetworkInterface

使用NetworkInterface类获得网络接口信息,调用NetworkInterface.getNetworkInterfaces()获取所有网络接口,也可以调用NetworkInterface.getByName(String)通过名称获取网络接口。
public static void main(String[] args) throws SocketException {Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();while (interfaces.hasMoreElements()) {NetworkInterface ni = interfaces.nextElement();System.out.println(ni);}}
2、InetAddress
使用InetAddress类来获得制定域名的地址信息,调用InetAddress.getByName(String)来获取地址,也可以调用InetAddress.getLocalHost()来获取本地地址。
public static void main(String[] args) throws UnknownHostException {InetAddress addr = InetAddress.getByName("www.baidu.com");System.out.println(addr.getHostName() + "/" + addr.getHostAddress());addr = InetAddress.getLocalHost();System.out.println(addr.getHostName() + "/" + addr.getHostAddress());}

3、Socket

Socket主要用来收发服务器数据。

(1) 主要方法

socket.getInputStream():接收服务器输入
socket.getOutputStream():发送服务器输出
socket.getInetAddress():服务器地址
socket.getPort():服务器端口号
socket.getLocalAddress():本地地址
socket.getLocalPort():本地端口号
socket.shutdownInput():半关闭输入
socket.shutdownOutput():半关闭输出

(2) Socket 的选项

1.TCP_NODELAY,是否使用Nagle算法
Socket.setTcpNoDelay(boolean),设置为true表示立即发送数据包。
2.SO_TIMEOUT,指定系统等待的时间
socket.setSoTimeout(int),0为一直等待,为默认值。
3.SO_LINGER,指定Socket关闭后如何处理尚未发送的数据包
socket.setSoLinger(boolean, int),设置为true时,close()方法会被阻塞指定的秒数,等待发送数据和接受确认。
4.SO_SNDBUF,设置发送缓存区大小
socket.setSendBufferSize(int)。
5.SO_RCV_BUF,设置接收缓存区大小
socket.setReceiveBufferSize(int)。
6.SO_KEEPALIVE,设置是否与服务器保持连接
socket.setKeepAlive(boolean)
7.OOBINLINE,发送单字节紧急数据
socket.setOOBInline(boolean)
socket.sendUrgentData(int)
8.SO_REUSEADDR,是否允许重用Socket所绑定的本地地址
socket.setReuseAddress(boolean)
9.IP_TOS,设置不同性能要求
socket.setTrafficClass(int)


0 0
原创粉丝点击