Java TCP/IP socket programming (14)

Source: Internet
Author: User
4.2 blocking and timeout

Socket I/O calls may be blocked for multiple reasons. The data input methods read () and receive () are blocked when no data is readable. The write () method of TCP socket may block when there is not enough space to cache transmitted data.


4.2.1 accept (), read () and receive ()

For these methods, we can use the setsotimeout () method of the socket, serversocket, and initramsocket classes to set the maximum blocking time (in milliseconds ). If these methods are not returned within the specified time, an interruptedioexception is thrown. For a socket instance, before calling the read () method, we can also use the inputstream available () method of the socket to check whether there is readable data.

4.2.2 connect and write data

The socket constructor attempts to establish a connection based on the host and port specified in the parameter, and blocks the wait until the connection is established successfully or a system-defined timeout occurs. Unfortunately, the System-defined timeout is long, and Java does not provide any method to shorten it. To change this situation, you can use the socket class's no-parameter constructor, which returns a socket instance without a connection. To establish a connection, call the connect () method of the instance and specify a remote terminal and timeout time (milliseconds ).

The write () method call will also block the wait until the last byte is successfully written to the local cache of the TCP implementation. If the available cache space is smaller than the data to be written, some data must be successfully transmitted to the other end of the connection before the write () method is returned. Therefore, the total blocking time of the write () method depends on the application at the receiving end. Unfortunately, Java has not yet provided any method to make write () Time-out or interrupt it by other threads. Therefore, a protocol that can send a large amount of data on a socket instance may be blocked indefinitely.

4.2.3 restrict the time of each client

You can use the following protocol to limit the service time at the code level:

Package COM. suifeng. tcpip. chapter4; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; import java.net. socket; import Java. util. logging. logger;/*** protocol independent from the client server * @ author suifeng **/public class timelimitechoprotocol implements runnable {Private Static final int time_limit = 5000; private Static final int buffer_size = 32; private Socket socket; private logger; publi C timelimitechoprotocol (Socket socket, logger) {super (); this. socket = socket; this. logger = logger;} public static void handleechoclient (Socket socket, logger) {try {inputstream in = socket. getinputstream (); outputstream out = socket. getoutputstream (); int totalbytes = 0; int recvsize =-1; long endtime = system. currenttimemillis () + time_limit; int timebounds = time_limit; byte [] buffer = new B Yte [buffer_size]; // sets the read timeout value socket. setsotimeout (time_limit); // limits the service time to avoid timeout while (timebounds> 0 & (recvsize = in. read (buffer ))! =-1) {out. write (buffer, 0, recvsize); totalbytes + = recvsize; timebounds = (INT) (endtime-system. currenttimemillis (); // reset the timeout value socket. setsotimeout (timebounds);} logger.info (thread. currentthread (). getname () + "is handling ECHO now"); logger.info ("client" + socket. getremotesocketaddress () + "echoed" + totalbytes + "bytes");} catch (ioexception e) {logger. warning ("exception in Echo Protocol:" + E. getmessage (); E. printstacktrace ();} finally {try {socket. close ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}}@ overridepublic void run () {handleechoclient (socket, logger );}}

More than 4.3 recipients

Our sockets process communication between two entities, usually a server and a client. This one-to-one communication method is sometimes called Unicast (unicast ). Multiple Receivers may be interested in some information. In this case, we can unicast a data copy to each receiver, but this may be very inefficient. Because the same data is sent multiple times, it is a waste of bandwidth to unicast multiple copies of the same data on a network connection.

Fortunately, the network provides a more effective way to use bandwidth. We can hand over the packet copying work to the network, rather than the sender.

There are two types of one-to-many (one-to-many) services: Broadcast and Multicast (Multicast ). For broadcast, all hosts in the local network receive a copy of data. For multicast, a message is only sent to a multicast address. The network only distributes data to hosts that want to receive data sent to the multicast address. Generally, only UDP sockets allow broadcast or multicast.

4.3.1 Broadcast

Broadcast UDP data packets are similar to unicast data packets. The only difference is that they use a broadcast address instead of a conventional (unicast) ip address. Note that IPv6 does not explicitly provide broadcast addresses. However,There is a special full node (All-nodes), link-local-scope multicast address, ffo2: 1, messages sent to this address are multicast to all nodes in a connection. IPv4's local broadcast address (255.255.255.255) sends messages to each host on the same broadcast network. The local broadcast information will never be forwarded by the router. A host on the Ethernet can send messages to other hosts on the same Ethernet, but the messages are not forwarded by the router. IPv4 also specifies a targeted broadcast address to broadcast to all hosts in the specified network.

There is no broadcast address that can send messages to all hosts in the network range. When a single data packet is sent at this address, the router may generate a large number of data packet copies, which may exhaust the bandwidth of all networks.

Even so, the local broadcast function is very useful. It is usually used to exchange status information between gamers in the same local (broadcast) network in online games.

4.3.2 Multicast

A multicast address indicates a group of recipients. IP protocol designers allocate a certain range of address space for multicast. The multicast address range of IPv4 is 224.0.0.0 to 239.255.255.255. The multicast address range of IPv6 is any address starting with ff.

The following is an example of sending messages through multicast.

Package COM. suifeng. tcpip. chapter4.multicast; import Java. io. ioexception; import java.net. datagrampacket; import java.net. inetaddress; import java.net. multicastsocket; import java.net. unknownhostexception; import COM. suifeng. tcpip. chapter3.vote. votemsg; import COM. suifeng. tcpip. chapter3.vote. votemsgcoder; import COM. suifeng. tcpip. chapter3.vote. votemsgtextcoder; public class votemulticastsender {public static Final int candidate = 888; public static void main (string [] ARGs) throws ioexception {If (ARGs. length <2 | args. length> 3) {Throw new illegalargumentexception ("parameters: <multicast address> <port> [<TTL>]");} inetaddress destaddress = inetaddress. getbyname (ARGs [0]); // check whether it is a multicast address if (! Destaddress. ismulticastaddress () {Throw new illegalargumentexception ("not a multicast address");} int destport = integer. parseint (ARGs [1]); int TTL = (ARGs. length = 3 )? Integer. parseint (ARGs [2]): 1; multicastsocket = new multicastsocket (); // sets the packet declaration cycle multicastsocket. setttl (byte) TTL); votemsgcoder coder = new votemsgtextcoder (); votemsg vote = new votemsg (true, true, candidate, interval 1l ); // sort the message byte [] MSG = coder. towire (vote); datagrampacket message = new datagrampacket (MSG, MSG. length, destaddress, destport); system. out. println ("Sending text-encode request (" + MSG. length + "bytes)"); system. out. println (vote); // sends the message multicastsocket. send (Message); multicastsocket. close ();}}

Differences between multicast sending and unicast sending: 1. Verify whether a given address is a multicast address; 2. Set the initial TTL (time to live, lifecycle ).

Network Multicast only sends messages to a specified group of receivers, which are called multicast groups.

Package COM. suifeng. tcpip. chapter4.multicast; import Java. io. ioexception; import java.net. datagrampacket; import java.net. inetaddress; import java.net. multicastsocket; import Java. util. arrays; import COM. suifeng. tcpip. chapter3.vote. votemsg; import COM. suifeng. tcpip. chapter3.vote. votemsgcoder; import COM. suifeng. tcpip. chapter3.vote. votemsgtextcoder; public class votemulticastreceiver {public static void main (String [] ARGs) throws ioexception {If (ARGs. length! = 2) {Throw new illegalargumentexception ("parameters: <muticast ADDR> <port>");} inetaddress address = inetaddress. getbyname (ARGs [0]); // check whether it is a multicast address if (! Address. ismulticastaddress () {Throw new illegalargumentexception ("not a multicast address");} int Port = integer. parseint (ARGs [1]); multicastsocket = new multicastsocket (port); // you can specify the multicast address of the message to be obtained. joingroup (Address); votemsgcoder coder = new votemsgtextcoder (); system. out. println ("Your er is OK !!! Waiting for data from sender "); datagrampacket message = new datagrampacket (New byte [votemsgtextcoder. max_wire_length], votemsgtextcoder. max_wire_length); // receives the message multicastsocket. receive (Message); votemsg vote = coder. fromwire (arrays. copyofrange (message. getdata (), 0, message. getlength (); system. out. println ("received text-encoded request (" + message. getlength () + "bytes)"); system. out. println (vote); multicastsocket. close ();}}

Start the server

Start the client

View servers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.