Black Horse Programmer _ Network programming

Source: Internet
Author: User

--------- Java training, Android training, iOS training,.  NET training look forward to communicating with you! ------ One, overview:1,osi Five-layer protocol protocol with TCP:
2, each layer protocol introduction:OSI Reference Model:
1. Layer Physical layer:The main definition of physical equipment standards, such as the interface type of network cable, the interface type of optical fiber, the transmission rate of various transmission media. Its main role is to transmit the bitstream (that is, 1, 0 is converted to the current strength to carry out the transmission, after reaching the destination in the conversion to 1, 0, that is, we often say the digital-to-analog conversion and A/D conversion). This layer of data is called a bit.
2. Data Link layer:The main data received from the physical layer to the MAC address (network card address) encapsulation and unpacking. This layer of data is often called a frame. The device that works on this layer is the switch, which transmits the data through the switch.
3. Layer Network layer:The packet of IP address (example 192.168.0.1) is encapsulated and unpacked mainly from the data received from the lower layer. The device that works on this layer is the router, which is often called the data packet.
4. Layer Transport Layer:Defines a number of protocols and port numbers (WWW port 80, etc.) that transmit data, such as TCP (Transmission Control Protocol, low transmission efficiency, reliability, high transmission reliability requirements, data volume data), UDP (User Datagram Protocol, the opposite of TCP characteristics, for transmission reliability requirements are not high, Data that is small in volume, such as QQ chat data, is transmitted in this way. The main point is to segment and transmit the data received from the lower layer, and then reorganize after reaching the destination address. This layer of data is often called a segment.
5. Session Layer:A path for data transmission is established through the Transport Layer (port number: Transport port and receive port). Primarily initiates a session between your systems or accepts a session request (the device needs to know each other either IP or Mac or hostname)
6. Presentation layer:The main thing is to interpret the received data, encrypt and decrypt, compress and decompress (that is, what the computer can recognize, and what the adult can recognize (slices, sounds, etc.).
7. Application Layer:Mainly some terminal applications, such as FTP (all kinds of file download), the WEB (ie browsing), QQ and the like (it can be understood as we can see on the computer screen things.) is the terminal application).

3, network communication elements
IP Address: inetaddress
Identification of devices in the network 192.168.1.223
Hard to remember, host name available
Local loopback address: 127.0.0.1 host name: localhost
Port number:
The logical address used to identify the process, and the identity of the different processes
Valid ports: 0~65535, where the 0~1024 system uses or retains ports.
Port: Physical port.
Digital ID of the software application: Logical port.
Transport protocol:
Rules of Communication
Common protocols: TCP (Transmission Control Protocol), UDP (Data Datagram Protocol)

two, UDP transmission and TCP transmission:

1,UDP Transfer steps:
Datagramsocket and Datagrampacket
Set up the sending side, the receiving end.
Set up the data package.
Invokes the Send receive method of the socket.
Close the socket.
the sending and receiving ends are two separate running programs.

Sender: On the sending side, specify the destination IP and port in the packet object.
Datagramsocket ds = new Datagramsocket (); byte[] by = "HELLO,UDP". GetBytes ();D atagrampacket dp = new Datagrampacket (by,0,b Y.length,inetaddress.getbyname ("127.0.0.1"), 10000);d S.send (DP);d s.close ();

Receive side: On the receiving side, specify the port to listen on.

Datagramsocket ds = new Datagramsocket (10000); byte[] by = new BYTE[1024];D atagrampacket dp = new Datagrampacket (By,by.leng TH);d s.receive (DP); String str = new String (Dp.getdata (), 0,dp.getlength ()); System.out.println (str+ "--" +dp.getaddress ());d s.close ();

2,tcp Transfer steps:
Sockets and ServerSocket
Establish client and server side
After the connection is established, the data is transmitted through the IO stream in the socket.
Close socket
Similarly, the client and server side are two separate applications.

Client: The client needs to specify the IP address and port of the server, so that it can try to establish a connection, and if the connection fails, an exception occurs. The connection is successful, which means that the client and the server have established a channel, then the data can be transmitted through IO stream, and the socket object has provided the input stream and output stream object, which is obtained by getInputStream () and Getoutputstream (). After the end of the communication with the server, close the socket.


Establishes the object through the socket and specifies the server-side host and port to connect to.


Socket s = new socket ("192.168.1.1", 9999), outputstream out = S.getoutputstream (); Out.write ("Hello". GetBytes ()); S.close ();

Service side:
The server needs to be clear on which port it is going to process the data. When there is client access, to identify which client, you can obtain the connected client object through the Accept (), and through the object and the client through the IO stream data transmission. When the client access is complete, close the client. Set up a server to listen to a port

ServerSocket ss = new ServerSocket (9999); Socket s = ss.accept (); InputStream in = S.getinputstream (); byte[] buf = new Byte[1024];int num = In.read (BUF); String str = new string (buf,0,num); System.out.println (S.getinetaddress (). toString () + ":" +str); S.close (); Ss.close ();
UDP and TCP differences:
Udp:1. Encapsulates data and sources and purposes into a packet without establishing a connection. ---------for no connection.
2. The size of each datagram packet is within the limit of 64k.
3. Because there is no connection, is not reliable agreement.
4. No need to establish a connection, fast.
Even if it is not connected to the data sent, so the data may not be received, unreliable. Mainly used for video conferencing and so on, some lack of point data is not important, reliability requirements low, transmission economy applications.
Tcp:1. Establish a connection to form a channel for transmitting data.
2. Make large data transfer in the connection.
3. Complete the connection via three handshakes, which is a reliable protocol.
4. Because the connection must be established, the efficiency will be slightly lower.
Mainly used for data download, file transfer, reliability requirements of high application

two, Socket class:1, Introduction: This class implements a client socket (also called a "socket"). Sockets are the endpoints of communication between two machines. a socket is a mechanism that is provided for network services. Sockets are available at both ends of the communication. Network communication is actually the communication between sockets. Data is transmitted via IO between two sockets. 2, the Main method:
1, construction method: Socket() Create an SocketImpl socket from the system default type Socket(InetAddress address, int port) creates a stream socket and connects it to the specified port number for the specified IP address. Socket(String host, int port,InetAddress localAddr, int localPort) creates a socket and connects it to the specified remote port on the specified remote host.
2, other methods:    bind(SocketAddress bindpoint) binds a socket to a local address. close() Close the socket. Connect connect(SocketAddress endpoint) This socket to the server. Connect connect(SocketAddress endpoint, int timeout) This socket to the server and specify a timeout value. getInetAddress() Returns the address of the socket connection. getLocalAddress() Gets the local address of the socket binding. getPort() Returns the remote port that this socket is connected to. isClosed() returns the closed state of the socket. isConnected() Returns the connection state of the socket. toString() Convert this socket to a String . 3,serversocket Service-side code:
Package Server;import Java.io.ioexception;import Java.io.inputstream;import java.io.printwriter;import Java.net.serversocket;import Java.net.socket;public class Server {public static void main (string[] args) throws IOException {/* *  Customize Server service side *  get browser information. and feedback information. */SYSTEM.OUT.PRINTLN ("My server Run ...."); ServerSocket ss = new ServerSocket (9090); Socket s = ss.accept (); System.out.println (S.getinetaddress (). Gethostaddress () + ".... Connected");//Read the client's data. InputStream in = S.getinputstream (); byte[] buf = new Byte[1024];int len = In.read (BUF); String text = new string (buf,0,len-1); System.out.println (text);//Feedback data to the client. PrintWriter out = new PrintWriter (S.getoutputstream (), True) out.println ("<font color= ' Red ' size= ' 7 ' > Welcome to </ Font> "); S.close (); Ss.close ();}}










Black Horse Programmer _ 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.