Between [rpm] TCP / IP protocol Computer communications, transmission, socket transmission channel

#! /usr/bin/env python3

# -*- coding:utf-8 -*-

 

# TCP / IP Profile

# In order to put all the different types of computers around the world are connected, it is necessary to define a set of universal agreement, in order to achieve this goal the Internet, the Internet protocol suite (Internet Protocol Suite) is

# Common protocol standard. Internet is a combination of inter net and two words together, the intent is to connect 'network' of the network, with the Internet, any private network, as long as the support for this agreement, we can connected to the Internet.

# Although the Internet Protocol includes hundreds of protocol standards, but the two most important protocol is TCP and IP protocols, so we referred to as the Internet Protocol TCP / IP protocol.

 

# When communicating, they must know each other's identity, like e-mail must know each other's e-mail address. It is the IP address that uniquely identifies each computer on the Internet, similar to 123.123.123.123

# If a computer to simultaneously access two or more networks, such as a router, it will have two or more IP addresses, therefore, actually the IP address of the corresponding network interface of the computer, usually card.

 

#IP protocol is responsible for transmitting data from one computer to another computer through a network. Data is divided into small chunks and then transmitted via IP packet. Because Internet links complicated, often between two computers

# Multiple lines, therefore, the router is responsible for deciding how to forward an IP packet out. Characteristics of the IP packet is transmitted in blocks, via a plurality of routes, but does not guarantee reach, does not guarantee the order of arrival.

 

#IP address is actually a 32-bit integer (referred IPV4), IP address 192.168.0.1 string representation as actually the 32-bit integer data packets by 8 bits, in order to read.

# IPV6 address is actually a 128-bit integer, which is an upgraded version of the current use of IPV4, as a string similar to 2001: 0db8: 85a3: 0042: 1000: 8a2e: 0370: 7334.

#TCP protocol is based on IP protocols. TCP protocol is responsible for establishing a reliable connection between the two computers, in order to ensure that data packets arrive. TCP connection is established through a handshake agreement, then, for each IP packet number, to ensure that

# Other order they are received, if the package lost, it automatically re-issued.

# Many common higher-level protocols are based on TCP protocol, such as HTTP protocol for browser, sending SMTP protocols.

# An IP packet containing the data to be transmitted in addition, also contains a source IP address and destination IP address, source port and destination port.

 

# Port What is the role? In two days of computer communication, only send IP address is not enough, because the program ran multiple networks on the same computer. After an IP packet came in the end is to the browser or QQ, it is necessary to distinguish the port number.

# Each network operating system, application programs to the unique port number, so that the two processes to establish a network connection between two computers need their own IP address and port number.

 

# While establishing a process may also be linked to multiple computers, so it will apply a lot of ports.

 

#TCP Programming

 

#Socket is an abstract concept of network programming. Usually we use a Socket means 'to open a web link', to open a Socket need to know the IP address and port number of the target computer, and then specify the protocol type

# Can be.

 

 

 

 

Client #

# Most links are reliable TCP connection. When you create a TCP connection, called the client initiates the connection, called passive response server connection.

 

# For example, when we visited Sina in your browser, your computer is our client, the browser will initiate connections to the SAN server. If all goes well, Sina accepted our server connection,

# A TCP connection is established, the communication is to send back the page content.

 

# Import socket library

import socket 

# Create a socket

s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

#establish connection:

s.connect (( 'www.sina.com.cn', 80)) # is a parameter tuple, comprising address and port number.

 

When # Create Socket, AF_INET specify IPV4 protocol, if the use of more advanced IPV6, it is specified as AF_INET6. SOCK_STREAM specifies the use of stream-oriented TCP protocol, so that creates a Socket object

# Successful, but no connection is established.

 

# Client to initiate TCP connections, you must know the IP address and port number of the server. IP addresses can be automatically converted Sina website with the domain name to an IP address www.sina.com.cn, but how to know which port the server Sina it?

# The answer is as a server, what kind of service, the port number must be fixed. Because we want to access web pages, Sina provide web services server port number must be fixed in 80-port, 80-port because

# Is the standard port for web services. Other service has a corresponding standard port number, such as port 25 SMTP service, FTP service port is 21, and so on. Port is the port number less than 1024, the standard port number of internet services

# Greater than 1024, it can be arbitrarily used.

 

# After establishing a TCP connection, we can send a request to a server Sina, asked to return to home page content:

 

#send data:

s.send(b'GET / HTTP/1.1\r\nHost:www.sina.com.cn\r\nConnection: close\r\n\r\n')

 

#TCP connections created a two-way channel, both sides can simultaneously send data to each other. But who should send the hair, how to coordinate, to be determined according to a specific protocol. For example, Http client agreement must send requests to

# Server, the server receives the data sent to the client after.

 

# Sending text format must comply Http standard, if the format is no problem, then you can receive the data returned by the server Sina:

#Receive data

buffer=[]

while True:

    # 1k bytes up to each reception:

    d=s.recv(1024)

    if d:

        buffer.append(d)

    else:

        break 

data=b''.join(buffer)

When receiving data # call recv (max) method, up to a specified number of bytes received, therefore, received in a while loop repeatedly until the recv () returns a null data representing received, exit the loop.

 

# When we finished receiving data, call the close () method to close the Socket, so, a complete network communication is over:

 

# Close the connection:

s.close()

 

# Received data including the HTTP header and the page itself, we only need to look at the HTTP headers and page separation, the HTTP header print out, save the page contents to a file:

header,html=data.split(b'\r\n\r\n',1)

print(header.decode('utf-8'))

# The received data written to the file:

with open('sina.html','wb') as f:

    f.write(html)

 

# Now, only need to open the sina.html file in a browser, you can see the home page of Sina.

 

#server 

# And client programming as compared to server programming can be more complicated.

 

# Server process must first bind a port and listens for connections from other clients. If a client connects over, and the server is established with the client Socket connection, and then rely on this communication Soket connected.

# Therefore, the server will open the fixed port (such as 80) to listen, each connected to a client, it creates the Socket connection. Because there will be a large number of server connections from the client, so to be able to distinguish between a server

#Socket connected and which is bound to the client. Socket dependent on a 4: server address, server port, client address, client port to uniquely identify a Socket.

# But the server also need to respond to requests from multiple clients, so that each connection requires a new process or a new thread to handle, otherwise, a server can only service a client of.

# Let's write a simple server program that accepts client connections, the client sent me a string with Hello again send back.

 

# Create a protocol based on IPV4 and TCP Socket:

s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

# Then we listen to bind address and port. The server may have multiple network cards, can be bound to an IP address of a network card, you can also use 0.0.0.0 to bind to all network address, you can also use 127.0.0.1

# Bind local address. 127.0.0.1 is a special IP address, local address representation, if bound to this address, the client must be running in order to connect the machine, that is, an external computer can not connect to come.

 

# Port number needs to be specified in advance. Because we write this service is not a standard service, so use this port number 9999. Please note that port numbers less than 1024 must have administrator privileges to bind:

 

# Listening port:

s.bind(('127.0.0.1',9999))

# Then, call the listen () method starts listening port, the incoming parameter specifies the maximum number of waiting connections:

s.listen(5)

print('Waiting for connection...')

 

# Next, the server program by connecting a permanent loop to receive from the client, Accept () returns and waits for a connection to the client:

while True:

    # Receives a new connection:

 sock,addr=s.accept()

 # Create a new thread to handle TCP connection:

 t=threading.Thread(target=tcplink,args=(sock,addr))

 t.start()

 # Each connection must create a new thread (or process) to deal with, otherwise, in the course of a single-threaded process connection, you can not receive other client connections:

def tcplink(sock,addr):

    print('Accept new connection from %s:%s...' % addr)

 sock.send(b'Welcome!')

 while True:

     data=sock.recv(1024)

  time.sleep(1)

  if not data or data.decode('utf-8')=='exit':

      break 

  sock.send(('Hello,%s!' % data.decode('utf-8')).encode('utf-8'))

 sock.close()

 print('Connection from %s:%s closed.' %addr)

# After the connection is established, the server first send a welcome message, and then wait for client data, plus Hello again sent to the client. If the client sends the string exit, to close the connection.

# To test the server program, we also need to write a client program:

s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

#establish connection:

s.connect(('127.0.0.1',9999))

# Receive the welcome message:

print(s.recv(1024).decode('utf-8'))

for data in [b'Michael',b'Tracy',b'Sarah']:

    #send data:

 s.send(data)

 print(s.recv(1024).decode('utf-8'))

s.send(b'exit')

s.close()

 

# We need to open two command-line window, run a server program, another program running the client, you can see the effect:

 

# Note that the client withdrew from the program is complete, the server program will run forever, you must exit the program press Ctrl + C.

 

# For the TCP protocol is very simple Socket Programming in Python, for the client to take the initiative and specify the IP connection port of the server, for the server, specify the port to listen first, then for every new connection,

# Create a thread or process to deal with. Typically, the server program will continue to run indefinitely.

 

# Same port, after a Socket is bound, can not be anything else Socket bound.


---------------------
Author: Ting Ming
Source: CNBLOGS
Original: https: //www.cnblogs.com/Ting-light/p/9548121.html
copyright Disclaimer: This article is the author original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/vilogy/p/12333915.html