Java Socket(转载)

来源:互联网 发布:淘宝首页 编辑:程序博客网 时间:2024/05/03 09:14

======================================================
注:本文源代码点此下载
======================================================

sockets let you send raw streams of bytes back and forth between twocomputers, giving you fairly low-level access to the tcp/ip protocol.see the file i/o amanuensis for sample code to do that. in tcp/ip eachcomputer has a name, such as roedy.mindprod.com. however, various tcp/ipprograms could be running on that computer. each socketgets a assigned a number called a port. the http server would usuallybe assigned 80. dbanywhere is usually 8889. this way you can specifywhich service on the local or remote machine you want to connect with.the socket is specified like this: roedy.mindprod.com:8889.

socket提供了在主机之间 传递原始字节流的功能,以比较底层的方式访问tcp/ip协议层.可以类似访问文件i/o的方式实现这一功能(在unix中,系统资源是以文件的方式进行访问的,其中也包括网络资源).tcp/ip协议规定,每台主机都有一个名称,例如roedy.mindprod.com.然而,同一台主机上有可能同时运行很多tcp/ip程序.每个socket被指派了一个叫做端口的数字以加以区分不同的应用或者连接.http应用服务器的端口一般被指定为80,dbanywhere通常指定为8889.我们通过这种方式区分你向远程或者本地主机请求连接的服务.一个socket被定义为 地址:端口, 例如 roedy.mindprod.com:8889

flush / 刷新

if you write to a socket,you usually need to call flush to force the data out onto the net. ifyou fail to do that, you could wait forever for a response because yourcomplete query was never sent. you don’t need flush if you are sending asteady stream of data that will push earlier data out onto the net.

如果向一个socket写入数据,通常需要调用flush方法去把数据发送到网络.如果操作失败,可能由于完整的请求信息未曾发送成功而导致持续等待响应.如果使用稳定的数据流的方式,不需要调用flush方法,因为数据流会自动把先前的数据发送到网络.

blocking read / 读堵塞

if you read from a socket, you can hang waiting forever if you use a blocking read. socket.setsotimeout controls the timeout. the read will eventually die when the socket connection fails. this will happen when:

* you close the socket at this end.

* the far end sends a disconnect signal.

* tcp cannot get an acknowlegement for packets it has sent,even after several retransmissions. these packets could either be datasent by theapplication, or keep-alive messages (if keep-alive has been turned on).don’t confuse this with the meaningless http keep-alive parameter.

由socket读取数据时,如果使用堵塞的读操作,可能会导致永久地等待.socket的setsotimeout方法 控制了超时的期限.在socket连接失败的情况下,读取数据的操作最终会被停止.

这种情况通常发生在以下几种情况:

1.本地关闭了socket,

2.远程主机/终端发送了断开连接的信号,

3.tcp协议实现在尝试多次重发数据仍无法获得对方针对已发送数据包的确认信息,或者无法获得keep-alive的信息(如果tcp协议的keep-alive选项已经被启用).另外不要和http协议的keep-alive参数相混淆.(http的keep-alive选项是指客户端与服务器之间建 立有效的长连接,避免了重复建立连接的消耗,尤其对提供静态资源访问的网站能够很大的提高访问效率)

timeouts /超时

java offers socket.setsotimeout to control how long you are willing to wait for a read to complete and socket.setsolingerto control how long it lingers, (waits to close when there are stillunsent data). when you shutdown, the other end should continue to readany buffered data to let the other end close before closing itself.setsotimeout has no effect on how long you are willing to wait for awrite (how long you are willing to wait for the other end to acceptdata), just on how long you are willing to wait for the other end toproduce data.

to add to the misery, windows partially ignores the timeout. onconnect, the jvm tries to resolve the hostname to ip/port. windows triesa netbios ns query on udp port 137 with a timeout of 1.5 seconds,ignores any icmp port unreachable packets and repeats this two moretimes, adding up to a value of 4.5 seconds. i suggest putting criticalhostnames in your hosts file to make sure they are resolved quickly.another possibility is turning off netbios altogether and running puretcp/ip on your lan.

socket的java实 现接口提供了setsotimeout方法设置希望等待完成读取操作的时间期限,提供setsolinger方法控制关闭等待期限(等待尚未发送的数据, 然后关闭连接). 当一方关闭连接时,另一方仍会在读取到缓冲区中的通知关闭连接的数据以后关闭连接(这句话不知道这样翻译是 否准确,不过实际操作应该是这样的,可以这样理解,当一端单方面关闭连接的时候,应该通知另一方你已经关闭连接,以便对方获悉并且关闭连 接).setsotimeout选项对等待完成写操作的期限没有影响(等待对方对方接收数据的期限),只和等待对方产生数据的期限有关. (setsotimeout和对方发送响应数据是否超时有关和对方何时接收数据没有关系).

比较令人苦闷的是,windows系统不负责任地忽略超时.对于一个连接.java虚 拟机努力将域名解析为ip地址和端口号.而windows使用udp的137端口向域名解析服务器发送域名解析查询,超时设为1.5秒.忽略了任何的icmp端口不可访问的数据包并且连续再重复发送两次相同的请求(一共是 三次).总计需要等待4.5秒.因此强烈建议把常用的域名地址和对应的ip地址和端口写在hosts文件中以确保可以迅速解析.另外就是在局域网完全中关 闭windows的netbios服务,完全使用tcp/ip访问资源.

disconnet detection / 探测连接关闭

since tcp/ip sends no packets except when there is traffic, without socket.setkeepalive(true ), it has no way of noticing a disconnect until you start tryingto send (or to a certain extent receive) traffic again. java has the socket.setkeepalive(true ) method to ask tcp/ip to handle heartbeat probing without anydata packets or application programming. unfortunately, you can’t tellit how frequently to send the heartbeat probes. if the other end doesnot respond in time, you will get a socketexception on your pending read. heartbeat packets in both directionslet the other end know you are still there. a heartbeat packet is justan ordinary tcp/ip ack packet without any piggybacking data.

当网络繁忙的时候,tcp/ip无法发送数据包.如果没有设定socket的setkeepalive为true,我们无法获悉一个连接已经关闭除非试图再次进行发送操作(或者进行某些接收操作).java通过设定socket的setkeepalive为true的方式要求tcp/ip协议进行心跳检测,不需要发送任何数据包或者应用级别的编程.然而不幸地是你无法肯定tcp/ip以怎样的频率发送心跳探测信号.如果另一方无法及时响应,当你试图进行读取操作的时候就会产生socket的异常.心跳包使双方都能获知对方是否保持连接.心跳包只是一个普通的tcp/ip的ack报文不需要搭载任何的其他数据.

when the applications are idling, your applications couldperiodically send tiny heartbeat messages to each other. the receivercould just ignore them. however, they force the tcp/ip protocol to checkif the other end is still alive. these are not part of the tcp/ipprotocol. you would have to build them into your application protocols.they act as are-you-still-alive? messages. i have found java’sconnection continuity testing to be less that 100% reliable. mybullet-proof technique to detect disconnect is to have the server sendan application-level heartbeat packet if it has not sent some packet inthe last 30 seconds. it has to send some message every 30 seconds, notnecessarily a dummy heartbeat packet. the heartbeat packets thus onlyappear when the server is idling. otherwise normal traffic acts as theheartbeat. the applet detects the lack of traffic on disconnect andautomatically restarts the connection. the downside is your applicationshave to be aware of these heartbeats and they have to fit into whateverother protocol you are using, unlike relying on tcp/ip levelheartbeats.

当应用处于空闲状态的时候,你的应用可以间断地向彼此发送小的心跳信息.接收者可以完全忽视它们,但是它们强制tcp/ip协议去核实另一方是否存活.这 不是tcp/ip协议通信规范的一部分,你需要建立自己的心跳协议,例如 发送内容为' are-you-still-alive?'的信息,原作者通过测试发现java的连 接持续性并非100%的可靠.他的银弹技术是通过服务端每隔30秒发送一个应用级别的心跳包,如果最近30秒内没有接收到任何数据包.服务器必须每隔30 秒发送一个数据包,不一定必须是傀儡的心跳数据包.心跳数据包只当服务器空闲的时候才会产生.否则的话,普通的网络通信就可以替代心跳数据包的功 能.applet探测发现由于断开连接导致的通信中断后就会重新建立连接.负面影响是你的应用必须时时关注这些心跳状态,并且如果你使用其它网络协议你也 要实现相应的心跳协议,不同余依赖于tcp/ip层的心跳.

however, it is simpler to use the built-in socket.setkeepalive(true ) method to ask tcp/ip to handle the heartbeat probing without anydata packets or application programming. each end with nothing to sayjust periodically sends an empty data packet with its current sequence,acknowledgement and window numbers.

然而,使用socket内置的setkeepalive(true)方法去要求tcp/ip进行心跳探测不使用任何数据包或者应用级别地编程实现看起来更加容易一些.每个终端只需间歇地发送一个包含当前序列的空的数据包,确认信息和滑动窗口号就可以了.

the advantage of application level heartbeats is they let you knowthe applications at both ends are alive, not just the communicationssoftware.

应用级别的心跳优点在于它们能够使你了解两端的应用都是否存活,而不在于只是通信软件.

server side socketing /服务器端套接字

for a server to accept connections from the outside world, first itopens a serversocket on a port, but not connected to any client inparticular.

对于一个接收外部连接的服务器,首先在某个没有连接任何客户端的端口上开启一个serversocket,代码如下

serversocket serversocket = new serversocket( port );

then it calls accept, which blocks until a call comes in.

socket clientsocket = serversocket.accept();

at that point a new ordinary socketgets created that is connected to the incoming caller. usually theserver would spin off a thread, or assign a thread from a pool to dealwith the new socket and loop back to do another accept.

当接收到一个请求时会新建一个的普通的socket,通常服务器会启动一个线程或者由线程池中取出一个线程处理新产生的socket,然后循环处理下一个请求.

you can set up your miniature server even if you don’t have a domain name. they can get to you byname: ip:port e.g. 65.110.21.43:2222. even if your are behind afirewall, you use the external facing ip of the firewall. you must thenconfigure your firewall to let incoming calls through and to direct themto the correct server on the lan.

即使你并不拥有一个域名,你也可以建立自己的服务器.他人可以通过ip地址和端口的方式( e.g.65.110.21.43:2222)访问你的服务器(如果在广域网上这要求你拥有自己的固定ip,这一般比拥有域名的成本还要高,不过在局域网内你可以 尝试局域网地址),如果你在处于防火墙保护的局域网内,你可以使用防火墙的对外ip.你必须配置你的防火墙以便请求数据包可以通过并且访问局域网内正确的 服务器.

flow control / 流控制

with socket.setreceivebuffersize()you can hint to the underlying os how much to buffer up incoming data.it is not obligated to listen to you. don’t confuse this with the bufferon the bufferedinputstream. this is the lower level buffer on the raw socket.large buffers are not always desirable. using small buffers can tellthe other end you are getting behind, and it won’t send data as quickly.if the data is real time, and the amount of data sent is variabledepending on how fast you process it, large buffers mean you can get waybehind and never catch up.

使用socket的setreceivebuffersize()方法你可以告诉底层的操作系统缓存多大的接收数据.但是这并非完全由你决定.不要将 socket的缓冲区和bufferedinputstream的缓冲区混淆.这是原始socket的 底层的缓冲区.过大的缓冲区并不总能很好地满足需要.使用小的缓冲区能够通知另一端你的处理速度已经落后了,因此对方不会继续马上发送数据过来(大的缓冲 区,对方发送过来的数据有可能还没有读取并被处理,但还留有很大的空间,因此对方会继续发送数据填满余下的空间,但是有可能导致大量的数据堆积在缓冲区中 无法处理,理想状态是使用小的缓存区,处理完当前数据后在接收,处理下一个数据).如果数据不是实时的,发送过来的数据量动态地依赖于处理数据的速度,过 大的缓冲区会导致你处理的数据量一直落后于接收的数据量,并且永远无法赶上.

there is a mysterioous method socket.settcpnodelay(true ) to "disable nagle’s algorithm". as is typical, there is noexplanation what nagle’s algorinthm is. my tcp/ip text book makes nomention of it. if you are dealing with near real-time data then you maywant to look into disabling nagle’s algorithm. that algorithm attemptsto ensure that tcp doesn’t send lots of undersized ip packets bybuffering-up submitted data and keeping it for typically for a fewmilliseconds to see if you are going to give it some more data thatcould go into the same packet. i am not sure if flush is sufficient tosend a packet on its way immediately.

socket的settcpnodelay(true )很神秘地用来关闭nagle算法.正如这里不解释nagle算法一样,这里也不讨论这个settcpnodelay方法.如果你处理近乎实时的数据,你可能会研究如何关闭nagle算法.nagle算法通过暂存已经提交发送的数据包许多毫秒的时间以便判断是否还需要向这个数 据包写入更多数据,确保tcp不发送大量的长度过小的数据包.我不确定是否flush方法能够充分地立即发送一个数据包.

graceful shutdown / 优雅地关闭

if you simply close a socket,you can lose data that were previously sent but which have not yet beendelivered. you may chop things off in mid message. so, how to shut downgracefully? my approach is this. when the client wants to shut down, itsends a close message. the server echos it back and on receipt of theclose message, the client closes the socket.that way the client is guaranteed to be unhooked from waiting on aread, and you are guaranteed the server and client each recieved thelast remaining messages before the socket was closed.

如果你简单地关闭一个socket连 接,你可能会丢失先前发送但并未抵达(交付)的数据.这可能会导致数据不完整.所以,如果优雅地关闭连接呢?作者的理论是:当客户端试图关闭连接时,它首 先要发送一条关闭信息.服务器原样返回关闭信息内容和确认关闭信息(增加确认关闭信息的做法可能是为了避免发送超时的数据包返回给发送者,两者内容可能是 相同的),客户端收到确认信息后关闭连接.这时客户端要确保解除等待读取操作的状态,并且你要确保客户端和服务器在关闭前都收到了最后的信息.


======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/
原创粉丝点击