Java Network Programming

Source: Internet
Author: User
Tags acer

One: OSI model

Open System Interconnection interconnect

Two: TCP/IP layered model

TCP on behalf of Transmission Control Protocol: Transfer Protocol allows reliable communication before two programs

UDP on behalf of Subscriber message Protocol: User Datagram Protocol allows unreliable communication before two programs

Three clients and servers

Four: Sockets

Definition: Socket (socket) is an abstraction layer through which applications send and receive data

Five: The InetAddress class represents an IP address, there is no constructor but there are multiple methods to query the API documentation.

Six: TCP socket programming

Server:

–1. Use ServerSocket to establish a port on the server for monitoring.

such as: ServerSocket server = new ServerSocket (8000);

–2. Using the Accept method to create a service-side socket

such as: socket socket = server.accept ()

–3. Creating an input-output stream with an established socket

such as: BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

–4. Close the input and output stream, close the socket, close the server

such as: Br.close ();

Pw.close ();

Socket.close ();

1  Packageinetaddress;2 3 /**4 * Server5  */6 ImportJava.io.BufferedReader;7 ImportJava.io.BufferedWriter;8 ImportJava.io.InputStreamReader;9 ImportJava.io.OutputStreamWriter;Ten ImportJava.net.ServerSocket; One ImportJava.net.Socket; A  -  Public classServertest { -  the      Public Static voidMain (string[] args)throwsException { -         //1 Creating a ServerSocket object specifying the port number -ServerSocket Server =NewServerSocket (30001); -Server.setsotimeout (10000); +         //2 waiting for customer to connect accept return type socket -Socket socket =server.accept (); +         //3 read data from client Socket.getinputstream () ABufferedReader reader =NewBufferedReader (NewInputStreamReader ( at Socket.getinputstream ())); -         Char[] ch =New Char[100]; -         intLen =reader.read (CH); -SYSTEM.OUT.PRINTLN ("Message received from client:"); -System.out.println (NewString (CH, 0, Len)); -         //3 Writing data to the client Socket.getoutputstream () inBufferedWriter Write =NewBufferedWriter (NewOutputStreamWriter ( - Socket.getoutputstream ())); toWrite.write ("We have received the message.")); + Write.flush (); -         //4 Releasing Resources the reader.close (); * socket.close (); $ write.close ();Panax Notoginseng  -     } the  +}

Client:

–1. Create a client socket to initiate a connection request to the server

such as: socket socket = new Socket ("127.0.0.1", 8000);

–2: Creating an input-output stream with an established socket

such as: BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

–3. Close the input and output stream, close the socket, close the server

such as: Br.close ();

Pw.close ();

Socket.close ();

1  Packageinetaddress;2 3 /**4 * Client5  */6 ImportJava.io.BufferedReader;7 ImportJava.io.BufferedWriter;8 ImportJava.io.InputStreamReader;9 ImportJava.io.OutputStreamWriter;Ten ImportJava.net.Socket; One  A  Public classCLIEBT { -  -      Public Static voidMain (string[] args)throwsException { the         //1 Creating the Socket object host Port -Socket socket =NewSocket ("127.0.0.1", 30001); -         //2 Write data to the server. Getoutputstream () -BufferedWriter Write =NewBufferedWriter (NewOutputStreamWriter ( + Socket.getoutputstream ())); -Write.write ("Hello server"); + Write.flush (); A         //2 read out the data. getInputStream () atBufferedReader reader =NewBufferedReader (NewInputStreamReader ( - Socket.getinputstream ())); -         Char[] ch =New Char[100]; -         intLen =reader.read (CH); -SYSTEM.OUT.PRINTLN ("Data"); -System.out.println (NewString (CH, 0, Len)); in         //3 Releasing Resources - reader.close (); to write.close (); + socket.close (); -     } the  *}

Seven: UDP socket programming

User Message Protocol (UDP) is a non-connection protocol used to send binary data from one computer to another. The data is called a datagram packet, which contains the destination server and port number to which the data will be sent. The Send () and receive () Methods of the Datagramsocket class have a datagrampacket parameter.
1  Packagechap18udp;2 3 Importjava.io.IOException;4 ImportJava.net.DatagramPacket;5 ImportJava.net.DatagramSocket;6 7 /**8 * Send9  * Ten  * @authorAcer One  * A  */ -  Public classSender { -  the      Public Static voidMain (string[] args)throwsIOException { -         //* 1 Creating Datagramsocket Objects -Datagramsocket Scoket =NewDatagramsocket (3000); -         //* * Create a Datagrampacket object +         byte[] buffer = "Hello". GetBytes (); -         intPort = 30001; +Datagrampacket packet =Newdatagrampacket (buffer, buffer.length, A scoket.getinetaddress (). Getlocalhost (), port); at         //3 Using Send - scoket.send (packet); -SYSTEM.OUT.PRINTLN ("Sending message"); -         //Freeing Resources - scoket.close (); -  in     } -  to}

The following steps are required to receive a datagram packet: 1. Create a byte array that is large enough to store the data for the package to receive. 2. Instantiate a Datagrampacket object using this byte array. 3. Datagramsocket is instantiated, which specifies a port on the local host to which the socket is bound. 4. Call the Receive () method of the Datagramsocket class to pass the Datagrampacket object into the method. This causes the execution thread to block until a datagram packet is received or a timeout occurs
1  Packagechap18udp;2 3 ImportJava.net.DatagramPacket;4 ImportJava.net.DatagramSocket;5 6 /**7 * Receive8  * 9  * @authorAcerTen  * One  */ A  Public classReciver { -  -      Public Static voidMain (string[] args)throwsException { the         //creating a byte array -         byte[] buffer =New byte[1024]; -         //2 Creating a Datagrampacket object -Datagrampacket packet =Newdatagrampacket (buffer, buffer.length); +         //3 Creating a Datagramsocket object -Datagramsocket socket =NewDatagramsocket (30001); +         //4 Using the Receive method A socket.receive (packet); atSYSTEM.OUT.PRINTLN ("Receiving information from" + packet.getsocketaddress () + ")); -System.out.println (NewString (Packet.getdata ())); -         //Freeing Resources - socket.close (); -  -     } in  -}
P Send datagram packet requires the following steps: • 1. Create a byte array that is large enough to store the packet data to be sent and populate the array with that data. ·2. Creates a new Datagrampacket object that stores the byte array above, along with the server name and the recipient's port number. ·3. Datagramsocket is instantiated that specifies which port of the socket to bind to the local host. 4. The Send () method of the Datagramsocket class is called, passing in the Datagrampacket object.

Java 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.