Black Horse Programmer--network programming (previous)

Source: Internet
Author: User
Tags closing tag

------>java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

The Java language is the first language to fully integrate into the web, and the Java language is a lot more suitable for writing Web applications. All terminal devices connected to the Internet (including computers, PDAs, printers, and other electronic devices) have a unique index called an IP address. IP addresses on the internet are now mostly made up of four bytes, the IP address called IPv4. In addition to this four-byte IP, there is an IP on the internet that consists of 16 bytes, called IPv6. The number behind IPV4 and IPV6 is the version number of the Internet Protocol (Internet Protocol,ip).

Network communication requires three basic conditions:

1. Find the other IP;
2. The data is sent to the application specified by the other party, in order to identify these applications, so that these network applications are identified by a number, in order to conveniently address this number, called the port or the logical port. Port range 0~65536, usually 0~1024 used or reserved by the system.

3. Define the communication rules, which are called protocols. International organizations define common protocol TCP/IP, commonly used protocols and UDP.
The transfer of data in the ISO seven layer model is actually the packet and unpacking process of the data.

The InetAddress class is the class used in Java to describe IP addresses. It is in the java.net package. InetAddress does not have a public construction method, so to create a InetAddress object, you must rely on its four static methods. InetAddress can get the InetAddress object of native by Getlocalhost method, also can get the Getallbyname object of remote host through Getbyname, Getbyaddress and InetAddress.

Use Getlocalhost to get the InetAddress object that describes the native IP. The Getbyname method is the most commonly used method of the InetAddress class. It can obtain the corresponding IP address from DNS by specifying the domain name. Getbyname A string parameter that allows you to specify the domain name of the remote host.

Use the Getallbyname method to get all the IP addresses for the domain name from DNS. This method returns an array of type inetaddress.

The Getbyaddress method must create an InetAddress object through an IP address, and the IP address must be in the form of a byte array.

The demo code is as follows:

Import Java.net.*;class Ipdemo {public static void main (string[] args) throws exception{//inetaddress I =inetaddress.getl Ocalhost ();  Get the native address//system.out.println (i.ToString ()), inetaddress  ia= inetaddress.getbyname ("www.baidu.com");  Get Baidu's host address and hostname System.out.println ("Address:" +ia.gethostaddress ()); System.out.println ("Name:" +ia.gethostname ());}}
Network application is divided into two parts, client and server, andThe socket class is the Java class responsible for handling client communication. This class allows you to connect to a server that specifies an IP or domain name, and can send and receive data to and from the server. The General network client program takes the following three steps when connecting to a service program:

1. Connecting to a server2. Sending and receiving data3. Turn off network connections
There are two ways in which a client can connect to a server, one is to connect to the server via IP, and the other is to connect to the server through a domain name.
In many programming languages or development tools (such as C + +, Delphi) using the domain name method to connect to the server, you must first resolve the domain name to IP, and then connect via IP, and in Java has already included the domain name resolution function in the socket class, therefore, We only need to use the domain name just like using IP. The most common way to connect a server program through the socket class is to pass the IP or domain name and port number as parameters into the socket class through the socket class's constructor.

in theThe two most important methods in the socket class are getInputStream and Getoutputstream. These two methods are used to obtain the InputStream and OutputStream objects used to read and write data, respectively. Here InputStream reads the data that the server program sends to the client, and OutputStream is the data that the client sends to the service-side program.

The two commonly used protocols in network communication are TCP and UDP protocols, which are distinguished as follows:

UDP: For no connection, the data and source and destination are encapsulated in the packet, no connection is required before the data is sent, and each packet size is limited to 64k. Because there is no connection, is unreliable protocol, no need to establish a connection, fast. Chat, video conferencing, all using the UDP protocol.
TCP: Establishes the connection, forms the data transmission channel, carries on the big data quantity transmission during the connection process, completes the transmission through three times handshake (in? In, I know you are in), is a reliable protocol, must establish a connection, the efficiency is slightly lower. The download is using the TCP protocol.


Here is a little exercise, the need: to move over the UDP transmission, a piece of text data sent out.

Idea: 1. Establish Udpsocket service;
2. Provide data and encapsulate the data in a packet
3. Send data packets via the socket service's sending function
4. Close the resource. The code is implemented as follows:

Import java.net.*;class  udpsend{public static void Main (string[] args) throws Exception{datagramsocket ds = new Datag Ramsocket ();  Create the UDP service//Determine the data and encapsulate it into packet datagrampacket (byte[] buf,int length,inetaddress address,int port) byte[] buf= "UDP laile". GetBytes ();D atagrampacket dp = new Datagrampacket (Buf,buf.length,inetaddress.getbyname ("192.168.1.101"), 10000); Ds.send (DP); Send packet Ds.close ();}}

Requirements: Define an application that receives the data transmitted by the UDP protocol and processes
Ideas: 1. Define Udpsocket services;
2. Define a packet to store the received byte data, because there are more functions in the packet object, extracting different data information in the byte data;
3. The received data is deposited into a defined packet via the Receive method of the socket service;
4, through the unique functions of the packet object, these different data are taken out, printed in the console;
5, close the resource. Implementation code:

Class Udprece{public static void Main (string[] args) throws exception{datagramsocket ds = new Datagramsocket (10000);  Create Udpsocket Establish endpoint//define packet for storing data byte[] buf = new byte[1024];D atagrampacket dp = new Datagrampacket (buf,buf.length);// The received data is stored in the packet Ds.receive (DP) via the Receive method of the service;  Blocking method, no data is equal to//through the data packet method to get the data of the string IP = dp.getaddress (). gethostaddress (); String data = new String (Dp.getdata (), 0,dp.getlength ()); int port = Dp.getport (); System.out.println (ip+ "::" +data+ "::" +port);//ds.close ();  Close Resource}}
Exercise: Write a chat program,

Analysis: The data collection and the data section, requires two threads, respectively, responsible for receiving and sending, because the collection and launch of inconsistent, so to define two run methods, and the two methods to be encapsulated in different classes.

Import Java.net.*;import Java.io.*;class Send implements Runnable{private datagramsocket ds;public Send (datagramsocket DS) {This.ds=ds;} public void Run () {try{BufferedReader bufr = new BufferedReader (new InputStreamReader (system.in)); String line = null;while (line = Bufr.readline ())!=null) {if (' 886 '. Equals line)//If Send 886, end of chat program break;byte[] buf= line . GetBytes ();D atagrampacket dp=new datagrampacket (Buf,buf.length,inetaddress.getbyname ("192.168.1.101"), 10002); Ds.send (DP);}} catch (Exception e) {throw new RuntimeException ("Send side Failed");}}} Class Rece implements Runnable{private datagramsocket ds;public rece (datagramsocket ds) {this.ds=ds;}  public void Run () {Try{while (true)//loop receive {byte[] buf = new byte[1024]; The data is received into the packet datagrampacket DP = new Datagrampacket (buf,buf.length);d s.receive (DP); String IP = dp.getaddress (). gethostaddress (); String Data=new string (Dp.getdata (), 0,dp.getlength ()); System.out.println (ip+ "::" +data);}} catch (Exception e) {throw new RuntimeException ("Receive Side Failed");}}} Class Chatdemo{public static void Main (string[] args) throws exception{datagramsocket sendsocket= new Datagramsocket (); Datagramsocket recesocket= New Datagramsocket (10002); New Thread (New Send (Sendsocket)). Start (); New Thread (New Rece (Recesocket)). Start ();}}

TCP Transport sub-client and server, the corresponding objects are sockets and ServerSocket.
Client: By looking up the socket object, it is found that the object can connect to the specified host when it is established, because TCP is connection-oriented, so when the socket service is established, there must be a service side, and the connection is successful, and then the channel is transmitted.

Requirement: Send a text data to the server
Step 1. Create a Socket object that specifies the host and port to connect to;

2. Send the data. The implementation code is as follows:

Import java.io.*;import java.net.*;class tcpclient{public static void Main (string[] args) throws exception{// Create a server-side socket object that specifies the host and port to connect to socket s=new socket ("192.168.1.101", 10003);  In order to send data, get the output stream in the socket stream OutputStream out=s.getoutputstream (); Out.write ("TCP data comes Up". GetBytes ()); S.close ();}}

Requirements: Define endpoints to receive data and print on the console
Server: 1. Set up the socket service on the server, ServerSocket (), and listen to a port;
2. Get connected Client object, through ServerSocket's Accept method, no connection will wait, this method is blocking method;
3. If the client sends over the data, the server will use the corresponding client object and fetch the read stream of the server object, and read the data sent.
4. Turn off the server (optional).

Class  tcpserver{public static void Main (string[] args) throws Exception{serversocket ss=new ServerSocket (10003); 1.//Gets the client object connected through the Acept method socket s=ss.accept (); String ip=s.getinetaddress (). gethostaddress (); System.out.println (ip+ "... connected");//Gets the data sent by the client, uses the read stream of the client object to read the data InputStream in=s.getinputstream (); byte[ ] buf=new Byte[1024];int len = In.read (BUF); System.out.println (New String (Buf,0,len)); S.close ();//Close client Ss.close ();}}

TCP Communication Practices:

Requirements: Set up a text conversion server, the client sends the text to the service side, the service side converts the text to uppercase and then returns it to the client. And the client can continue to do text conversion, the client input over when the conversion is over.
Analysis:
Client: Since the operation of the data on the device, you can use IO technology, and according to the operational rules of IO thinking.
Source: Keyboard entry. Purpose: Network device, network output stream, operation is text data, optional character stream.
Steps:
1. Establishment of services; 2. access to keyboard entry; 3. Send data to the server; 4. Go to the server to return capital data; 5. End, close resources. Are text data that can be manipulated using a character stream while increasing efficiency and adding buffering.

Implementation code:

Import java.io.*;import java.net.*;class transclient{public static void Main (string[] args) throws Exception{socket S=ne W Socket ("192.168.1.101", 10005);//defines the stream object that reads the keyboard data BufferedReader bufr =new BufferedReader (New InputStreamReader ( system.in));//source//Define the purpose of writing data to the socket output stream and send it to the server BufferedWriter bufout=new bufferedwriter (New OutputStreamWriter ( S.getoutputstream ())); Purpose//define a socket read stream to read uppercase information returned by the server BufferedReader bufin=new BufferedReader (New InputStreamReader (S.getinputstream ()) ); String Line=null;while (Line =bufr.readline ())!=null) {if (' over '. Equals (line)] Break;bufout.write (line);  Bufout.newline (); Line break, end tag Bufout.flush (); String Str=bufin.readline (); System.out.println ("Server::" + str);} Bufr.close (); S.close ();}} Class Transserver{public static void Main (string[] args) throws Exception{serversocket ss=new ServerSocket (10005); Socket s =ss.accept (); String ip= s.getinetaddress (). gethostaddress (); System.out.println (ip+ "... connected");//Read the data in the socket read stream BufferedReader bufin=new BufferedReader (New InputStreamReader (S.getinputstream ()));//purpose, socket output stream, writes uppercase data to the socket output stream, and sends it to the client BufferedWriter bufout=new BufferedWriter (New OutputStreamWriter (S.getoutputstream ())); String Line=null;while (Line =bufin.readline ())!=null) {System.out.println (line); Bufout.write (Line.touppercase ())  ; Bufout.newline (); Line break, end tag Bufout.flush ();} S.close (); Ss.close ();}}

The problem of writing code: The phenomenon: the client and the service side are in inexplicable wait;

Cause: Both the client and the server have a blocking method that waits until the end tag is read. Workaround: Add a line break as the closing tag.



Black Horse Programmer--network programming (previous)

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.