Java Foundation _java Network programming __c language

Source: Internet
Author: User
Network Programming Port: Physical Port:

Is the routing of the interface, can be inserted line, see, Touch the logical port:

Used to identify the logical address of a process, identification of different processes, valid ports: 0~65535, where the 0~1024 system uses or retains ports.

IP object in Java: InetAddress.

Import java.net.*;
Class  ipdemo{public
    static void Main (string[] args) throws unknownhostexception{
        //By name (IP string or host name) To get an IP object.
        inetaddress IP = inetaddress.getbyname ("www.baidu.com");//java.net.unknownhostexception
        System.out.println ("Addr:" +ip.gethostaddress ());
        System.out.println ("Name:" +ip.gethostname ());
    }
}
socket: Socket, end of communication

is to provide a mechanism for network services, communication at both ends of the socket, network communication is the socket between the communication, data in two sockets between the IO transmission. UDP Transport: as long as the network transmission, there must be a socket. Data must be encapsulated in a packet, including destination address, port, data, and other information.

Direct operation of UDP is not possible, for the Java language should be encapsulated UDP into objects, easy to use, this object is Datagramsocket. The socket object that encapsulates the UDP transport protocol.

Because the packet contains more information, in order to manipulate this information convenient, it will also be packaged as an object. This packet object is: Datagrampacket. Through the methods in this object, you can get the various information in the packet.

Datagramsocket has the ability to send and accept, in the UDP transmission, need to be clear one is the sender, one is the receiver side. UDP Sender: set up UDP socket service, when the object is created without an explicit port, the system will automatically allocate an unused port. Specify the specific data to send. Encapsulates the data into a packet. Send the data packages using the Send method of the socket service. Closes the resource.

Import java.net.*;
Class  udpsend{public
    static void Main (string[] args) throws Exception {
//      1, to establish the UDP socket service.
        datagramsocket ds = new Datagramsocket (8888);//Specify the send port, do not specify that the system is randomly assigned.
//      2, specify the specific data to be sent.
        String Text = "UDP transmission demo buddy came";
        byte[] buf = Text.getbytes ();      3, the data is encapsulated into a packet.
        Datagrampacket dp = new Datagrampacket (buf,
buf.length,inetaddress.getbyname ("10.1.31.127"), 10000);      4, use the socket service Send method to send the data packages.
        Ds.send (DP);      5, close the resource.
        ds.close ();
    }

receiving end of UDP:To create a UDP socket service, you must have a clear port that only the data sent to this port is the data that the receiving end can handle. Defines a packet that is used to store received data. The receiving method of the socket service is used to store the received data in the packet. The data packet is used to get the specific data content in the packet, such as IP, port, data and so on. Closes the resource.
Class Udprece {public
    static void Main (string[] args) throws exception{
//      1 to create a UDP socket service.
        datagramsocket ds = new Datagramsocket (10000);      2, defines a packet that is used to store incoming data. First defines the byte array, which stores the data in a byte array.
        byte[] buf = new byte[1024];
        Datagrampacket DP = new Datagrampacket (buf,buf.length);      3, the receiving method of the socket service is used to store the received data in the packet.
        Ds.receive (DP);//This method is a blocking method.
//      4, through the packet method to obtain data packets in the specific data content, such as IP, port, data and so on.
        String IP = dp.getaddress (). gethostaddress ();
        int port = Dp.getport ();
        String text = new String (Dp.getdata (), 0,dp.getlength ());//Convert a valid part of a byte array to a string.
        System.out.println (ip+ ":" +port+ "--" +text);      5, close the resource.
        ds.close ();
    }
TCP Transport:

A two-endpoint connection will have a channel to transmit data, called a stream, and a stream based on the network, called the socket stream. There are both reads and writes in the stream. two endpoints of TCP:

One is the client, the other is the service side.
Client: Corresponding object, Socket
Server side: Corresponding object, ServerSocket TCP client: establish the TCP socket service, it is best to specify the specific address and port. When this object is created, it can already connect to the specified IP and port (three handshake). If the connection succeeds, it means that the channel is established and the socket stream has been generated. As long as the read stream and the write stream in the socket stream are obtained, two stream objects can be obtained by getInputStream and Getoutputstream. Closes the resource.

Import java.net.*;
Import java.io.*;
Requirements: The client sends a data to the server side.
class  tcpclient{public
    static void Main (string[] args) throws exception{
        socket s = new socket ("10.1.31.69", 10002); C8/>outputstream out = S.getoutputstream ();//Gets the output stream object in the socket stream.
        out.write ("TCP demo, dude again!"). GetBytes ());
        S.close ();
    }
TCP service side:Create a service-side socket service and listen for a port. In order to provide services to clients, obtain the content of the client, you can obtain the connected client object through the Accept method. You can communicate through the socket stream in the socket object that you get to and the specific client. If the communication is over, close the resource. Note: To close the client first, then turn off the service side.
class tcpserver{public static void Main (string[) args) throws exception{Serversock ET ss = new ServerSocket (10002);//Set up service socket socket s = ss.accept ()//Get client object String IP = S.getinetadd
        Ress (). gethostaddress ();
System.out.println (ip+ "... connected");
        You can communicate through the socket stream in the socket object that you get to and the specific client.
        InputStream in = S.getinputstream ()//Read client data, use socket read stream of client object byte[] buf = new byte[1024];
        int len = In.read (BUF);
        String text = new string (Buf,0,len);
System.out.println (text); If the communication is over, close the resource.
        Note: To turn off the client first, on the service side.
        S.close ();
    Ss.close (); }
}

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.