Java socket Programming (IV)

Source: Internet
Author: User
Tags socket string client port number
Programming duplicates and concurrent servers

All of these calls can throw a unknownhostexception violation. If a computer is not connected to a DNS server, or if the host does not find it, the violation is thrown. If a computer does not have an activated TCP/IP configuration, Getlocalhost () is also a failure and throws an offence.

Once an address is identified, the datagram can be sent out. 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 to an array of bytes. Then a new Datagrampacket instance must be built. Note the last two parameters of the builder. The address and port must be given if a packet is to be sent. An applet may be able to know the address of its server, But how does the server know its client's address? When any packet is received, the returned address and Port are decompressed and obtained via the getaddress () and Getport () methods. This is how a server responds to a client's package:

Datagrampacket sendpacket = new Datagrampacket (SendBuf, Sendbuf.length,
Recvpacket.getaddress (), Recvpacket.getport ());
Serversocket.send (Sendpacket);

Unlike a connection-oriented operation, a datagram server server is actually simpler than a datagram client:

Datagram Server

Basic steps for a datagram server:

1. Establish a datagram socket on a specified port.

2. Wait for incoming packages using the Receive method.

3. Respond to received packages with a specific protocol.

4. Go back to step two or move on to the second step.

5. Close the datagram socket.

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

Listing 9.3. A Simple datagram response server

Import java.io.*;
Import java.net.*;
public class Simpledatagramserver
{
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 simpledatagramserver:" + se);
}
catch (IOException IoE)
{
System.out.println ("Error in Simpledatagramserver:" + IoE);



This application is treated as a duplicate server. Because it accepts another connection only after it has finished processing a process. More complex servers are concurrent. It assigns a thread to each request, Instead of one to deal with one. So it looks like it's dealing with multiple requests at the same time. All commercial servers are concurrent servers.

Java Datagram class

Unlike a connection-oriented class, the datagram's client and server-side classes are the same on the surface. The following program establishes a datagram sockets for a client and server provider:

Datagramsocket ServerSocket = new Datagramsocket (4545);
Datagramsocket clientsocket = new Datagramsocket ();

The server uses parameter 4545来 to specify the port number, and the client can take advantage of the available ports because the client will call the server. If the second argument is omitted, the program assigns the operating system an available port. The client can request a specified port, but if other applications are already bound to this port, The request will fail. If your intention is not to be a server, it is best not to specify a port.

Since the stream cannot be obtained by conversation, how do I talk to a datagram socket? The answer is the datagram class.

Receive datagrams

The Datagrampacket class is a class that is used to receive and send data through the Datagramsocket class. The packet class includes connection information and data. As mentioned earlier, datagrams are independent transmission units. The Datagrampacket class compresses these cells. The following program represents 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 resulting data. A 512-byte cache is established and serves as the second parameter of the builder. Each two builder parameter is the size of the cache. Like the Accept () method of the ServerSocket class, receive () Method will block until the data is available.

Send Datagrams

Sending datagrams is very simple, all you need is an address. The address is created by the InetAddress class. This class does not have a common builder, but it has several static methods, Can be used to create an instance of this class. The following list lists the ways to establish an instance of the InetAddress class:

Public InetAddress Creation Methods

InetAddress Getbyname (String host);
Inetaddress[] Getallbyname (String host);
InetAddress Getlocalhost ();

It is very useful to get the address of the local host, only the first two methods are used to send the packet. Getbyname () and Getallbyname () require the address of the destination host. The first method is simply to return the first qualifying item. The second method is necessary, Because a computer may have more than one address. In this case, this computer is called multi-homed.

All established 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 ();



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.