Black Horse programmer _ network programming, black horse programmer Network Programming

Source: Internet
Author: User

Black Horse programmer _ network programming, black horse programmer Network Programming
--------- Java training, Android training, iOS training, and. Net training are coming to be discussed with you! ------I. Overview:1. layer-5 protocols combined with OSI and Tcp:
2. Introduction to protocols at different layers: OSI reference model:
1. Layer Physical Layer: It mainly defines physical device standards, such as the interface type of the network cable, the interface type of the optical fiber, and the transmission rate of various transmission media. Its main function is to transmit the bit stream (that is, the conversion from 1, 0 to the current strength for transmission, after reaching the destination is converted to 1, 0, that is, the digital-to-analog conversion and digital-to-analog conversion ). The data at this layer is called bits.
2. data link layer: encapsulate and unencapsulate the MAC address (NIC address) of the data received from the physical layer. This layer of data is often called frames. The device that works on this layer is a switch, and data is transmitted through the switch.
3. layer network layer: encapsulate and unencapsulate the data received from the lower layer (for example, 192.168.0.1. The device that works on this layer is a router, and data on this layer is often called a data packet.
4. transport Layer: defines some data transmission protocols and port numbers (WWW port 80, etc.), such as TCP (Transport Control Protocol, low transmission efficiency, high reliability, it is used for data with high transmission reliability requirements and a large amount of data) and UDP (User Datagram Protocol, which is opposite to TCP features. It is used for data with low transmission reliability requirements and small data volumes, for example, QQ chat data is transmitted in this way ). Data received from the lower layer is segmented and transmitted, and then reorganized after the destination address is reached. This layer of data is often called segments.
5. Session Layer: establishes a data transmission path through the transport layer (port number: Transmission port and receiving port. It is mainly used to initiate a session or receive a session request between your systems (devices need to know each other, either an IP address, a MAC address, or a host name)
6. presentation Layer: it mainly refers to interpreting, encrypting, decrypting, compressing, and decompression the received data (that is, converting what computers can recognize into something that adults can recognize (tablets, sounds, etc ).
7. application Layer: Mainly some terminal applications, such as FTP (various file downloads), WEB (IE browsing ), QQ and so on (we can understand it as something we can see on the computer screen. is the terminal application ).

3. network communication elements
IP Address: InetAddress
Identifier of the device in the Network: 192.168.1.223
Hard to remember, available Host Name
Local loopback address: 127.0.0.1 Host Name: localhost
Port Number:
Used to identify the logical address of a process.
Valid port: 0 ~ 65535, 0 ~ 1024 the system uses or retains the port.
Port: physical port.
The digital identifier of the software application: Logical port.
Transmission Protocol:
Communication rules
Common protocols: TCP (Transmission Control Protocol) and UDP (data packet reporting protocol)

Ii. UDP transmission and TCP transmission:

1. UDP transmission steps:
DatagramSocket and DatagramPacket
Set up the sender and acceptor.
Create a data packet.
Call the sending and receiving method of the Socket.
Disable Socket.
The sender and acceptor are two independent programs.

Sender: Specify the destination IP address and port in the data packet object.

DatagramSocket ds = new DatagramSocket();byte[] by = “hello,udp”.getBytes();DatagramPacket dp = new DatagramPacket(by,0,by.length,InetAddress.getByName(“127.0.0.1”),10000);ds.send(dp);ds.close();

Acceptor: Specify the listening port at the acceptor.

DatagramSocket ds = new DatagramSocket(10000);byte[] by = new byte[1024];DatagramPacket dp = new DatagramPacket(by,by.length);ds.receive(dp);String str = new String(dp.getData(),0,dp.getLength());System.out.println(str+"--"+dp.getAddress());ds.close();

2. TCP transmission steps:
Socket and ServerSocket
Create a client and a server
After the connection is established, data is transmitted through the IO stream in the Socket
Disable socket
Likewise, the client and the server are two independent applications.

Client: the client must specify the IP address and port of the server to establish a connection. If the connection fails, an exception occurs. The connection is successful, indicating that the client and the server have established a channel, so data can be transmitted through the IO stream, while the Socket object already provides the input stream and output stream object, through getInputStream (), getOutputStream. Close the Socket after communication with the server.


Establish an object through Socket and specify the server host and port to be connected.


Socket s = new Socket(“192.168.1.1”,9999);OutputStream out = s.getOutputStream();out.write(“hello”.getBytes());s.close();

Server:
The server must specify the port from which the data to be processed enters. When a client accesses the client, you must specify the client. You can use accept () to obtain the connected client object and transmit data with the client through the IO stream. When the access to the client ends, close the client. To create a server, you must 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();
Difference between UDP and TCP: 

UDP: 1. encapsulate data and source and target data into data packets without establishing a connection. --------- For non-connection.
2. The size of each datagram package is limited to 64 KB.
3. Because there is no connection, It is an unreliable protocol.
4. No connection is required, and the speed is fast.
No matter the connection fails, it sends data, so the data may not be received and unreliable. It is mainly used for video conferencing and chatting, and some applications with low reliability requirements and economic transmission are irrelevant to the lack of point data.
TCP: 1. Establish a connection to form a channel for data transmission.
2. Perform big data transmission in the connection.
3. It is a reliable protocol that completes the connection through three handshakes.
4. Because a connection must be established, the efficiency will be slightly lower.
It is mainly used for data download, file transmission, and applications with high reliability requirements.

Ii. Socket class:1. Introduction: This class implements the client socket (also known as "socket "). A socket is the end point for communication between two machines. Socket is a mechanism provided for network services. Both ends of the communication have sockets. Network Communication is actually the communication between sockets. Data is transmitted through IO between two sockets. 2. Main Methods:
1. constructor: Socket()Use SocketImpl of the default system type to create an unconnected socket Socket(InetAddress address, int port)Create a stream socket and connect it to the specified port number of the specified IP address. Socket(String host, int port,InetAddress localAddr, int localPort)Create a socket and connect it to the specified remote port on the specified remote host.
2. Other methods:    bind(SocketAddress bindpoint)Bind the socket to a local address. close()Disable this socket. connect(SocketAddress endpoint)Connect the socket to the server. connect(SocketAddress endpoint, int timeout)Connect the socket to the server and specify a timeout value. getInetAddress()Return the socket connection address. getLocalAddress()Obtain the local address bound to the socket. getPort()Returns the remote port to which the socket is connected. isClosed()The socket is closed. isConnected()Returns the connection status of the socket. toString()Convert this socket String. 3. ServerSocket server 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 {/** custom server Server * to obtain 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 client 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); // returns data to the client. PrintWriter out = new PrintWriter (s. getOutputStream (), true); out. println ("<font color = 'red' size = '7'> welcome </font>"); 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.