Build your own QQ using Java (1)

Source: Internet
Author: User

I once used VB to make a LAN chat applet. At that time, I just copied a source code, and the amount of code was very small. A total of only two hundred lines of code, and only two people can chat, I used a Winsock Control in VB. At that time, I had no idea about Winsock network programming, but now I am learning network programming. I wanted to use C # to implement it, but it is of little value to think about using C # To do something similar to QQ. In addition, I want to study java well during this time, so I am familiar with network programming and Java programming, why not?

First, introduce some knowledge about network programming:

It is very convenient and powerful to develop network software with Java. This power of Java comes from his unique set of powerful network-related APIs, which are a series of classes and interfaces, the packages are located in java.net and javax.net. In this article, we will introduce the socket concept and illustrate how to use network APIs to manipulate sockets. After this article, you can write low-end network communication software.

  What is socket )?

Network API is typically used to communicate with other programs based on TCP/IP network Java programs. Network API relies on socket for communication. The socket can be seen as an endpoint in the communication connection between two programs. One program writes a piece of information into the socket, and the socket sends this information to another socket, this information can be transmitted to other programs. 1

Let's analyze 1. program a on host a writes a piece of information into the socket, and the content of the socket is accessed by the network management software of host, the information is sent to host B through the network interface card of host a. The network interface card of host B receives the information and sends it to the network management software of host B, the Network Management Software saves this information in the socket of host B, and then program B can read this information in the socket.

Assuming that the third host C is added to the network in Figure 1, how does host a know that the information is correctly transmitted to host B rather than to host C? Each host in a TCP/IP network is assigned a unique IP address. The IP address is a 32-bit unsigned integer. Because it is not converted to binary, it is usually separated by decimal places, such: 198.163.227.6, as you can see, the IP address is composed of four parts, each of which ranges from 0 to 255, to represent an eight-bit address.

It is worth noting that the IP addresses are all 32-bit addresses, which are specified by ipprotocol version 4 (IPv4). At present, because IPv4 addresses are nearly exhausted, IPv6 addresses are gradually replacing IPv4 addresses, the IPv6 address is a 128-bit unsigned integer.

Assuming that the second program is added to host B of the network in Figure 1, how can the information sent from host a be correctly transmitted to program B instead of the newly added program? This is because every TCP/IP-based network communication program is assigned a unique port and port number. The port is an information buffer for retaining the input/output information in the socket, the port number is a 16-bit unsigned integer in the range of 0-65535, to distinguish every program on the host (the port number is like the room number in the House ), for example, the POP3 port number is 256, and each socket is combined into the IP address, port, and port number, in this way, we can differentiate every socket T. Next we will talk about two sockets: stream socket and self-addressing data socket.

  Stream socket)

At any time, a reliable connection is required for sending and receiving information between two network applications, and the stream socket relies on the TCP protocol to ensure that the information reaches the destination correctly. In fact, an IP packet may be lost in the network or an error occurs during transmission. In any case, the TCP of the receiver will contact the sender TCP to resend the IP packet. This is called establishing a reliable connection between two stream sockets.

Stream socket plays a necessary role in the C/S program, the client program (network applications that need to access certain services) create a stream socket object that acts as the IP address of the host and the port number of the server program (network application that provides services for client applications.

The initialization code of the client stream socket transmits the IP address and port number to the network management software of the client host, and the management software transmits the IP address and port number to the server host through Nic; the server host reads the data transmitted by the NIC, and then checks whether the server program is listening. This kind of listening is still performed through the socket and port. If the server program is listening, the network management software on the server sends a positive response signal to the client network management software. After receiving the response signal, the client stream socket initialization Code creates a port number for the client program, and pass the port number to the socket of the server program (the server program will use this port number to identify whether the incoming information belongs to the Client Program) and complete the initialization of the stream socket.

If the server program is not listening, the network management software on the server sends a negative signal to the client, the stream socket initialization code of the client program throws an exception object without establishing communication connections or creating a stream socket object. This is like making a phone call. When someone establishes a communication, the phone will be suspended.

This part of work includes three associated classes: inetaddress, socket, and serversocket. The inetaddress object depicts 32-bit or 128-bit IP addresses. The socket object represents the client program stream socket, and the serversocket represents the service program stream socket. All three classes are located in the java.net package.

  Inetaddress class

The inetaddress class plays an important role in Network API socket programming. Parameters are passed to the stream socket class and self-addressing socket class constructor or non-constructor method. Inetaddress describes 32-bit or 64-bit IP addresses. To complete this function, the inetaddress class mainly relies on two support classes: inet4address and inet6address. These three classes are inheritance relationships and inetaddrress is the parent class, inet4address and inet6address are subclasses.

Because the inetaddress class has only one constructor and cannot pass parameters, you cannot directly create an inetaddress object. For example, the following method is incorrect:

Inetaddress IA = new inetaddress ();

However, we can create an inetaddress object or an inetaddress array using the following five factory methods:

. The getallbyname (string host) method returns a reference to an inetaddress object. Each object contains a separate IP address indicating the corresponding host name, which is passed through the host parameter, if no IP address exists for the specified host, this method will throw an unknownhostexception object.

. The getbyaddress (byte [] ADDR) method returns a reference to an inetaddress object, which contains an IPv4 address or IPv6 address. The IPv4 address is a 4-byte array, the IPv6 address is a 16-byte address array. If the returned array is neither 4-byte nor 16-byte, the method will throw an unknownhostexception object.

. The getbyaddress (string host, byte [] ADDR) method returns a reference to an inetaddress object, which contains an IP address specified by the host and a 4-byte ADDR array, or the IP address specified by the host and 16-byte ADDR arrays. If the array is neither 4-byte nor 16-byte, this method will throw an unknownhostexception object.

. The getbyname (string host) method returns an inetaddress object, which contains an IP address corresponding to the host specified by the host parameter. If no IP address exists for the specified host, the method throws an unknownhostexception object.

. The getlocalhost () method returns an inetaddress object, which contains the IP address of the Local Machine. Considering that the local host is both a client host and a server host, to avoid confusion, we call a client host and a server host.

The methods mentioned above all mention returning one or more references to the inetaddress object. In fact, each method returns a reference to one or more inet4address/inet6address objects, the caller does not need to know the referenced subtype. On the contrary, the caller can use the returned reference to call the non-static method of the inetaddress object, including the subtype polymorphism to ensure that the overloaded method is called.

The inetaddress and its child-type object process the conversion from the host name to the IPv4 or IPv6 address of the host. To complete this conversion, you need to use the domain name system. The following Code demonstrates how to call getbyname (string host) method to obtain the inetaddress subclass object. This object contains the IP address corresponding to the host parameter:

Inetaddress IA = inetaddress. getbyname ("www.javajeff.com "));

Once the inetaddress subclass object is referenced, you can call various inetaddress methods to obtain the IP address information in the inetaddress subclass object. For example, you can call getcanonicalhostname () get the standard host name from the Domain Name Service; gethostaddress () Get the IP address; gethostname () Get the host name; isloopbackaddress () judge whether the IP address is a loopback address.

List1 is a Demo code: inetaddressdemo

// Inetaddressdemo. Java

Import java.net .*;

Class inetaddressdemo
{
Public static void main (string [] ARGs) throws unknownhostexception
{
String host = "localhost ";

If (ARGs. Length = 1)
Host = ARGs [0];

Inetaddress IA = inetaddress. getbyname (host );

System. Out. println ("canonical host name =" +
IA. getcanonicalhostname ());
System. Out. println ("host address =" +
IA. gethostaddress ());
System. Out. println ("host name =" +
IA. gethostname ());
System. Out. println ("is loopback address =" +
IA. isloopbackaddress ());
}
}

When there is no command line parameter, the code output is similar to the following result:

Canonical host name = localhost
Host address = 127.0.0.1
Host Name = localhost
Is loopback address = true

Inetaddressdemo gives you a selection of the specified host name as a command line parameter. If no host name is specified, localhost (client) is used. inetaddressdemo calls getbyname (string host) method to obtain the reference of an inetaddress subclass object. The reference obtains the output of the standard Host Name, host address, host name, and whether the IP address is a loopback address.

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.