Dark Horse programmer--java High-tech--network programming

Source: Internet
Author: User

Click Open Link Click Open Link click Open link android training, <a "> Click Open Link click Open link Java training, look forward to communicating with you! > Click the Open link to open the link

Network Programming Network Model

L OSI Reference Model

L TCP/IP Reference Model

Network communication elements

L IP Address: The identity of the device in the network, not easy to remember, the available host name, local loopback address,127.0.0.1 hostname:localhost

L port number: Used to identify the logical address of the process, the identity of the different processes, the valid port:0~65535, where the 0~1024 system uses or retains the port

L Transport Protocol: Rules of Communication, common protocols:TCP,UDP

The general process of network communication

1. Find the other IP

2. The data is sent to the application specified by the other party, so that the network applications are identified with numbers in order to identify the applications. To conveniently address this number, called the port, the logical port. 0~65535

3. Define a communication rule. This communication rule becomes an agreement. The international organization defines the common protocol TCP/IP communication. UDP

InetAddress class: This class represents an Internet Protocol (IP) address

Static InetAddress | Getlocalhost (): get Local host

String | Gethostaddress (): returns the IP address string

String | GetHostName (): Gets The host name of this IP address

Static Inetadress | Getbyaddress (byte[] addr): returns the inetaddress Object Given the original IP Address

Static inetaddress | Getbyaddress (String host,byte[] addr): creates inetaddress based on the given host and IP address.

Static inetaddress | Getbyname (String host) determines the host's IP address in the case of a given host .

Static inetaddress[] | Getallbynames (String host): returns an array of its constituent names based on the name service configured on the system, given the host name.

TCP and UDP

UDP: chat, video conferencing

Encapsulates data and sources and purposes into packets without establishing a connection

Limit the size of each datagram within 64K

Because there is no connection, it is an unreliable agreement.

No need to establish connection, fast speed

TCP: Download

Establish a connection to form a channel for transmitting data

Make large data transfers in a connection

Complete connection via three handshake, is a reliable protocol

The connection must be established and the efficiency will be slightly lower

UDP transport

Datagramsocket class : This class represents the socket used to send and receive datagram packets.

Constructor:datagramsocket(int port): Specify Port

Datagramsocket():

Important methods:

void | Send (Datagrampacket p): sends a datagram packet

void | Receive (Datagrampacket p): receives datagram packet

Datagrampacket class: This class represents a datagram packet.

constructor function:

Datagrampacket (byte[] buf,int length)

Datagrampacket (byte[] buf,int length,inetaddress address,int Port)

Important methods:

inetaddress | GetAddress (): Returns the IP address that This datagram will be sent to or received from the host .

Byte[] | GetData (): returns buffer data

int | GetLength (): Returns the length of data that will be taken or received

int | Getport (): Gets the port that this datagram will be sent to or received from this host

A piece of text data is sent through the UDP transmission mode.

1. Establish updsocket service

2. Provide data and encapsulate the data in a packet

3. Send data packets via the socket service's sending function

4. Close Resources

Define an application that receives UDP -transmitted data and processes

1. Define the udpsocket service , usually receive a port, in fact, to the network application to define a digital ID, easy to identify what data come over the application can process.

2. Define a packet, because there are more features in the packet object that can advance different data information in the byte data in order to store the received data.

3. The received data is stored in a defined packet via the socket Service's receive method

4. Take these different data out and print them on the console using the unique features of the packet

5. Close Resources

UDP Exercises:

Import Java.util.*;import Java.io.*;import java.net.*;class UDP3 {public static void main (string[] args) {new Thread (new U DPSend3 ()). Start (); New Thread (New UDPReceive3 ()). Start ();}} Class UDPSend3 implements Runnable{public void Run () {try {datagramsocket ds=new datagramsocket ();//Create an IO stream to receive data b Ufferedreader br=new BufferedReader (New InputStreamReader (system.in)); for (String Str=br.readline (); str!=null;str= Br.readline ()) {byte[] buf=str.getbytes (); Datagrampacket dp=new Datagrampacket (Buf,buf.length,inetaddress.getlocalhost (), 1002); Ds.send (DP); if ("Over". Equals (str)) break;}      Ds.close ();      } catch (Exception e) {System.out.println (e); }}}class UDPReceive3 implements runnable{public void run () {try {datagramsocket ds=new-datagramsocket (100 2); while (true) {byte[] buf=new byte[1024];D atagrampacket dp=new datagrampacket (buf,buf.length);d s.receive (DP); String Info=new string (Buf,0,dp.getlength ()); System.out.println (Dp.getaddreSS () + "::" +info), if ("over". Equals (info));   Ds.close ();   } catch (Exception e) {System.out.println (e); }}}


TCP Transport

Sockets and serversocket

L Establish client and server side

• data transfer via IO stream in the Socket after connection is established

L Close Socket

In the same way, the client and server side are two separate applications.

Socket class: This class implements the customer service end socket

Common constructors: Socket () socket (inetaddress address,int port) socket ()

Common methods:

Void | Close (): close this socket

Void | Connect (socketaddress Endpoint): Connect This socket to the server.

inetadddress | Getinetaddress (): Returns the address of this socket connection

InputStream | getInputStream (): returns the input stream for this socket

OutputStream | Getoutputstream (): returns the output stream for this socket

Int | Getport (): Returns the remote port that this socket is connected to

Void | Shutdowninput (): the input stream for this socket is placed at the end of the stream.

Void | Shutdowmoutput (): disables the output stream for this socket.

Serversocke This class implements a server socket

Common constructors:ServerSocket () serversocket (int port)

Common methods:

sockets | Accept (): listens for and accepts connections to this socket

URL class: Represents a Uniform Resource locator, which is a pointer to the Internet "resource".

URL (String spec)

Important methods:

String | GetFile (): gets The file name of this URL

String | GetHost (): gets The host name of this URL

String | GetPath (): gets The path portion of this URL

String | Getprotocol (): gets The protocol name for this URL

String | Getquery (): gets the query portion of this URL

URLConnection | OpenConnection (): Returns a connection that represents the remote object referenced by the URL.

InputStream | OpenStream (): opens a connection to this URL and returns a inputstream to be read into from the connection .

URLConnection class: An abstract class that represents A communication connection between an application and a URL.

Important methods:

InputStream | getInputStream (): returns the input stream read from this open connection

OutputStream | Getoutputstream (): returns the input stream written to this link.

Client

by looking at the socket object, it is found that when the object is established, it is possible to connect to the specified host because TCP is connection-oriented, so when the socket service is established, Must have the service side exists, and the connection succeeds, forms the path, carries on the data transmission in this channel.

Steps:

1. Create the socket service and specify the host and port to connect to.

Socket (String host,int port);

2. In order to send data, you should get the output stream in the socket Stream

Getoutputstream ()

Write ()

3. Close the service

Service side

1. set up the socket serviceon the server,serversocket.

ServerSocket(int port) to answer a port

2. Get the client-side object connected.

Through the accept () method, get the Socket, no connection will wait, so this method is blocking

3. If the customer sends over the data, then the server uses the corresponding customer service object, and gets the read stream of the client to read the sent data and print it in the console.

4. Close the server (optional)

TCP Ultimate Exercise Import Java.net.*;import java.io.*;import java.awt.*;import java.awt.event.*;class tcp{private Frame F; Private TextField tf;private Button bt;private TextArea ta; TCP () {init ();} public void init () {f=new Frame ("my Browser"); F.setbounds (100,100,600,600); F.setlayout (new FlowLayout ()); Tf=new TextField        Bt=new button ("Go to"); Ta=new TextArea (30,66); F.add (TF); F.add (BT); F.add (TA); MyEvent (); f.setvisible (true);} public void MyEvent () {Bt.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {T    ry {ta.settext ("");    String Ip=tf.gettext ();    URL url=new url (IP);    URLConnection uc=url.openconnection ();    InputStream in = Uc.getinputstream ();    Byte[] Buf=new byte[1024];int len=0;    while ((Len=in.read (buf,0,buf.length))!=-1) {ta.append (new String (Buf,0,len)); }} catch (Exception ee) {throw new RuntimeException ("Login Server failed!            "); }}); F.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {system.exit (0);}}); public static void Main (string[] args) {new TCP ();}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dark Horse programmer--java High-tech--network programming

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.