Java Learning Notes (15) Java Network programming

Source: Internet
Author: User
Tags connect socket

The OSI model is divided into seven layers (bottom to top): Physical layer, Data link layer, network layer, transport layer, Session layer, presentation layer, application layer.

The same hierarchy between different hosts is called the peer layer. Communication between peers requires adherence to certain rules, called protocols, and we refer to a set of protocols running on a host as the protocol stack. The host is using this protocol stack to receive and send data.

TCP/IP model: Network interface layer, network interconnect layer, Transport layer, application layer.

Some of the issues to be aware of in network programming include:

1. Is how to find the network on the host to communicate the program;

2. Is how the data is transferred after the program on the host is found.

Port number: is a set of 16-bit unsigned binary numbers, and the range of each port number is 1 to 65535 (0 is reserved).

The TCP protocol represents a Transmission Control protocol that allows reliable communication between two applications;

The UDP protocol, which represents the user message protocol, is a non-connection protocol that allows unreliable communication between two applications. Provides protocols that are sent between applications called datagrams.

Socket sockets: The UNIX system introduces an operating system invocation of an application access communication protocol, an abstraction layer through which applications send and receive data.

Different types of sockets are associated with different types of underlying protocol families and different protocol stacks in the same protocol family.

The InetAddress class represents an IP address, for example:

Import Java.net.inetaddress;public class Inetaddresstest {public        static void Main (string[] args) throws Exception { c1/>inetaddress IP = inetaddress.getlocalhost ();       SYSTEM.OUT.PRINTLN (IP);       inetaddress IP = inetaddress.getbyname ("80ymekcc96rxaob");       SYSTEM.OUT.PRINTLN (IP);       inetaddress[] Allbyname = Inetaddress.getallbyname ("www.baidu.com");      for (inetaddress inetaddress:allbyname) {            System.out.println (inetaddress);       }             byte[] IP = {(byte) 192, (byte) 168, 1, n};             InetAddress address = inetaddress.getbyaddress ("www.baidu.com", IP);             SYSTEM.OUT.PRINTLN (address);}      }

  

To establish a TCP connection using sockets:

1. The server initializes a ServerSocket object that indicates which port number the communication will take.

2. The server calls the Accept () method of the ServerSocket class. The method waits until a client connects to the specified port on the server.

3. While the server waits, the client instantiates a socket object, specifying the server name and port number to connect to.

The constructor of the 4.Socket class attempts to connect the client to the specified server and port number.

5. On the server side, the Accept () method returns a reference to the new socket for the server that will connect to the client socket.

Import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.net.serversocket;import java.net.Socket;/           Server-side * * @author Administrator**/public Class Server {public static void main (string[] args) throws IOException {           Create a ServerSocket object that specifies the listening port serversocket server = new ServerSocket (30001);           Set timeout time server.setsotimeout (10000);            Wait for client to connect socket socket = server.accept (); /* Processing Client data *//Read data from client BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.getin           Putstream ()));            char[] ch = new CHAR[100];            int len = reader.read (CH);            SYSTEM.OUT.PRINTLN ("Information received from the client:");            while ( -1! = (len = reader.read (ch))) {System.out.print (New String (CH, 0, Len)); }//write data to client BufferedWriter writer = new BufFeredwriter (New OutputStreamWriter (Socket.getoutputstream ()));            Writer.write ("Hello client, I have received your information");              Writer.flush ();             Release resources Writer.close ();             Reader.close ();             Socket.close ();        Server.close (); }}

Import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.ioexception;import Java.io.inputstreamreader;import java.io.outputstreamwriter;import java.net.socket;/*** Client Request--response * * @author Administrator**/public class Client {public static void main (string[] args) throws IOException {//Gen             Create a client socket to the server to initiate a connection request socket SOCKET = new Socket ("192.168.1.200", 30001); /* Create an input/output stream with an established socket, process connections to the server///write data to the server BufferedWriter writer = new BufferedWriter (New OUTPU           Tstreamwriter (Socket.getoutputstream ()));            Writer.write ("Hello server!!!");          Writer.flush ();           Read data from the server BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));           char[] ch = new CHAR[100];           int len = reader.read (CH);            SYSTEM.OUT.PRINTLN ("Information received from server side:"); while ( -1! = (len = reader.read (ch))) {System.out.print (New String (CH,0, Len));          }//Release resources reader.close ();           Writer.close ();        Socket.close (); }}

  

UDP socket Programming

Both the sender and the recipient of the datagram package use the Java.net.DatagramSocket class to send and receive packets, respectively.

Receive packet:

1. Create a byte array that is large enough to store the data for the packet to be received;

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.

Import java.net.*;
Import java.io.*;

public class packetreceiver{

     public static void Main (string[] args) {            try{                   byte[] buffer = new byte [1024x768];                   Datagramoacket packet = new Datagrampacket (buffer,buffer.length);                   Datagramsocket socket = new Datagramsocket (5002);                   Syatem.out.println ("Waiting for a package ...");                   Socket.receive (packet);                   System.out.println ("Just from" + packet.getsocketaddress () + "receive package");                   Buffer = Packet.getdata ();                   System.out.println ("New String (buffer)");            catch (IOException e) {                    e.printstacktrace ();}}     }

Send Message Packet

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. Create a new Datagrampacket object that stores the byte array above, along with the server name and the recipient's port number;

The 3.DatagramSocket is instantiated, and it is specified which port the socket is bound to on the local host;

The Send () method of the 4.DatagramSocket class is called, passing in the Datagrampacket object.

Import Java.net.*;import java.io.*;p ublic class packetsender{public       static void Main (String [] args) {                 try{                       String data = "just received packet";                       byte[] buffer = data.getbytes ();                       Datagrampacket packet = new Datagrampacket (buffer,buffer.length,new inetsocketaddress ("localhost", 5002));                       Datagramsocket socket = new Datagramsocket (5003);                       SYSTEM.OUT.PRINTLN ("Sending a package ...");                       Socket.send (packet);                 } catch (IOException e) {                       e.printstacktrace ();}}        }

  

 

Java Learning Notes (15) 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.