Java网络编程从入门到精通(28):获取ServerSocket信息的方法及FTP原理

2014-11-24 00:05:12 · 作者: · 浏览: 0

ServerSocket对象相关的信息有两个:绑定端口和绑定IP地址。绑定端口可以通过getLocalPort方法获得。绑定IP地址可以通过getInetAddress方法获得。

一、getLocalPort方法

getLocalPort方法的返回值可分为以下三种情况:

1. ServerSocket对象未绑定端口,getLocalPort方法的返回值为-1

2. ServerSocket对象绑定了一个固定的端口,getLocalPort方法返回这个固定端口。

3. ServerSocket对象的绑定端口为0getLocalPort方法返回一个随机的端口(这类端口被称为匿名端口)。

getLocalPort方法的定义如下:

public int getLocalPort()

html1%5C01%5Cclip_filelist.xml" rel=File-List> getLocalPort方法主要是为这些匿名端口而准备的。下面的代码演示了ServerSocket对象产生随机端口的过程:

package server;

import java.net. * ;

public class RandomPort
{
public static void main(String[] args) throws Exception
{
for ( int i = 1 ; i <= 5 ; i ++ )
{
System.out.print(
" Random Port " + i + " " );
System.out.println(
new ServerSocket( 0 ).getLocalPort());
}
}
}

运行结果:

Random Port1: 1397
Random Port2:
1398
Random Port3:
1399
Random Port4:
1400
Random Port5:
1401

在大多数时候ServerSocket对象都会绑定一个固定的端口。但有时客户端只需要和服务端进行短暂的连接,这时就可以使用匿名端口。如我们经常用的FTP服务就是如此。

<script type="text/java script">BAIDU_CLB_fillSlot("771048");
点击复制链接 与好友分享! 回本站首页
<script> function copyToClipBoard(){ var clipBoardContent=document.title + '\r\n' + document.location; clipBoardContent+='\r\n'; window.clipboardData.setData("Text",clipBoardContent); alert("恭喜您!复制成功"); }
分享到: 更多
<script type="text/java script" id="bdshare_js" data="type=tools&uid=12732"> <script type="text/java script" id="bdshell_js"> <script type="text/java script"> var bds_config = {'snsKey':{'tsina':'2386826374','tqq':'5e544a8fdea646c5a5f3967871346eb8'}}; document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js cdnversion=" + Math.ceil(new Date()/3600000)