Java Network Programming

Source: Internet
Author: User

Http://www.cnblogs.com/hellokitty1/p/4474143.html

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 package inetaddress; 2 3/** 4 * Server 5 */6 import Java.io.BufferedReader; 7 Import Java.io.BufferedWriter; 8 Import Java.io.InputStreamReader; 9 Import java.io.outputstreamwriter;10 Import java.net.serversocket;11 import java.net.socket;12 public class         servertest {public static void main (string[] args) throws Exception {16//1 Create ServerSocket object Specify port number 17 ServerSocket Server = new ServerSocket (30001); Server.setsotimeout (10000); 19//2 waiting for Customer connection accept return type S OCKET20 Socket socket = server.accept (); 21//3 read data from client Socket.getinputstream () BufferedReader re Ader = new BufferedReader (New InputStreamReader (Socket.getinputstream ())), [char[] ch = new CH ar[100];25 int len = reader.read (ch); SYSTEM.OUT.PRINTLN ("Message received from client:"); System.out.println (NE W String (CH, 0, Len); 28//3 Write data to client Socket.getoutputstream () BufferedWriter write = new BufferedWriter ( New OUtputstreamwriter (Socket.getoutputstream ())); Write.write ("We have received the message"); Write.flus H (); 33//4 release Resources reader.close (); Socket.close (); Write.close (); 37 38}39 40}

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 package inetaddress; 2 3/** 4 * Client 5 */6 import Java.io.BufferedReader; 7 Import Java.io.BufferedWriter; 8 Import Java.io.InputStreamReader; 9 Import java.io.outputstreamwriter;10 Import java.net.socket;11 public class Cliebt {$ public static void main (string[] args) throws Exception {15//1 Create socket object host Port socket socket = new Socket ("127.0.0.1", 30001                  ); 17//2 writes data to the server. Getoutputstream () BufferedWriter write = new BufferedWriter (New OutputStreamWriter (19 Socket.getoutputstream ())), Write.write ("Hello server"), Write.flush (), 22//2 readout data. getInputStream () BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.geti Nputstream ())); char[] ch = new char[100];26 int len = reader.read (ch); SYSTEM.OUT.PRINTLN ("Data "); System.out.println (New String (CH, 0, Len); 29//3 Release resources: Reader.close (); writE.close (); Socket.close (); 33}34 35} 

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 package chap18udp; 2  3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6  7/** 8
   
    * Send 9 *  @author acer11  *12 */13 Public  class Sender {All public     static void Main (string[] Arg s) throws IOException {+         //* 1 Create Datagramsocket object         datagramsocket scoket = new Datagramsocket         /* * Create Datagrampacket object         byte[] buffer = "Hello". GetBytes ();         int port = 30001;21         Datagrampacket packet = n EW datagrampacket (buffer, buffer.length,22                 scoket.getinetaddress (). Getlocalhost (), port), +         //3 using SEND24         scoket.send (packet);         SYSTEM.OUT.PRINTLN ("Sending message"); +         //Release Resources         Scoket.close ();     }30 31}
   

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 package chap18udp; 2  3 import java.net.DatagramPacket; 4 import java.net.DatagramSocket; 5  6/** 7  * Receive 8  *  9  * @aut Hor Acer10  *11  */12 public class Reciver {$ public     static void Main (string[] args) throws Exception {15
   //Create byte array         byte[] buffer = new byte[1024];17         //2 Create Datagrampacket object         datagrampacket packet = new Data Grampacket (buffer, buffer.length); +         //3 Create Datagramsocket object         datagramsocket socket = new Datagramsocket ( 30001)         //4 using the Receive method of         socket.receive (packet);         System.out.println ("receiving from" + Packet.getsocketaddress () + "information");         System.out.println (New String (Packet.getdata ()));         //Release Resources 26         socket.close ();     29 30}
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

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.