Java Socket programming (4) duplicate and concurrent servers

Source: Internet
Author: User

 

Duplicate and concurrent servers

This application is treated as a duplicate server. because it only accepts another connection after processing a process. more complex servers are concurrent. it allocates a thread for each request, instead of processing one. so it seems that it is processing multi-user requests at the same time. all commercial servers are concurrent servers.

Java Datagram class

Unlike connection-oriented classes, the client-side and server-side classes of datagram are essentially the same. The following program creates the datagram sockets of a customer and Server Provider:

DatagramSocket serverSocket = new DatagramSocket (4545 );
DatagramSocket clientSocket = new DatagramSocket ();

The server uses parameter 4545 to specify the port number. Because the client will call the server, the client can use the available port. if the second parameter is omitted, the program assigns an available port to the operating system. the client can request a specified port, but if other applications have been bound to this port, the request will fail. if your intention is not to act as a server, it is best not to specify a port.

Because the stream cannot be obtained by the conversation, how can I talk to a datagram Socket? The answer is the datagram class.

Receive Datagram

The initrampacket class is used to receive and send data through the initramsocket class. the packet class includes connection information and data. as mentioned above, a datagram is an independent transmission unit. the DatagramPacket class compresses these units. the following program uses a datagram socket to receive data:

DatagramPacket packet = new DatagramPacket (new byte [512], 512); clientSocket. receive (packet );
ClientSocket. receive (packet );

The packet builder needs to know where to put the obtained data. A 512-byte cache is created and serves as the second parameter of the builder. each of the two builder parameters is the cache size. just like the accept () method of the ServerSocket class, the receive () method will block before data is available.

Send Datagram

Sending a datagram is very simple. All you need is an address. the address is created by the InetAddress class. this class does not have a public builder, but it has several static methods that can be used to create instances of this class. the following list lists how to create an InetAddress class instance:

Public InetAddress Creation Methods

InetAddress getByName (String host );
InetAddress [] getAllByName (String host );
InetAddress getLocalHost ();

It is very useful to obtain the address of the local host. Only the first two methods are used to send data packets. getByName () and getAllByName () require the address of the target host. the first method only returns the first thing that meets the condition. the second method is required because a computer may have multiple addresses. in this case, this computer is called multi-homed.

All created methods are marked as static. They must be called as follows:

InetAddress addr1 = InetAddress. getByName ("merlin ");
InetAddress addr2 [] = InetAddress. getAllByName ("merlin ");
InetAddress addr3 = InetAddress. getLocalHost ();

All these calls can roll outUnknownHostException violation. if a computer is not connected to the DNS server, or the host is not found, this violation will be thrown out. if a computer does not have an activated TCP/IP configuration, getLocalHost () throws an violation for failure.

Once an address is identified, the datagram can be sent. The following program transmits a string to the destination socket:

String toSend = "This is the data to send! ");
Byte [] sendbuf = new byte [toSend. length ()];
ToSend. getBytes (0, toSend. length (), sendbuf, 0 );
DatagramPacket sendPacket = new DatagramPacket (sendbuf, sendbuf. length,
Addr, port );
ClientSocket. send (sendPacket );

First, the string must be converted into a byte array. then, a new initrampacket instance must be created. note the last two parameters of the builder. to send a packet, the address and port must be specified. an applet may know its server address, but how does the server know its client address. when any package is received, the returned address and port are extracted and obtained through the getAddress () and getPort () methods. this is how a server responds to a client package:

DatagramPacket sendPacket = new DatagramPacket (sendbuf, sendbuf. length,
RecvPacket. getAddress (), recvPacket. getPort ());
ServerSocket. send (sendPacket );

Unlike connection-oriented operations, the datagram server is actually simpler than the datagram client:

Datagram Server

Basic Steps for a datagram Server:

1. Create a datagram socket on a specified port.

2. Use the receive method to wait for the incoming package.

3. Use specific protocols to respond to received packets.

4. Go back to step 2 or continue step 2.

5. Disable the datagram socket.

List 9.3 demonstrates a simple datagram response server. It will respond to the packets it receives.

List 9. 3. A simple datagram response Server

Import java. io .*;
Import java.net .*;
Public class simpledomainramserver
{
Public static void main (String [] args)
{
DatagramSocket socket = null;
DatagramPacket recvPacket, sendPacket;
Try
{
Socket = new DatagramSocket (4545 );
While (socket! = Null)
{
RecvPacket = new DatagramPacket (new byte [512], 512 );
Socket. receive (recvPacket );
SendPacket = new DatagramPacket (
RecvPacket. getData (), recvPacket. getLength (),
RecvPacket. getAddress (), recvPacket. getPort ());
Socket. send (sendPacket );
}
}
Catch (SocketException se)
{
System. out. println ("Error in simpledomainramserver:" + se );
}
Catch (IOException ioe)
{
System. out. println ("Error in simpledomainramserver:" + ioe );

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.