python --- socket acquaintance

python Network Programming (First solid)


Some concepts

Sockets:

Socket (socket), also known as communication endpoints, originally used for communication between the computer's internal processes, and with the development of the network, the socket is used for communication between computers. For example, you (a computer) to call to your friends (another computer), your friend's phone number just can not do, but also a desk phone, and this is equivalent to a telephone socket word.

There are two sockets based file, based on the network. Based on the file can be simply understood as a process of communication, it can be simply understood based network for communication between computers. And they were divided into different address family (address family, abstract names), such as AF_UNIX, AF_INET ... since it is the python network programming, first focus on AF_INET (use ipv4).

Amount ... there is a concept, connection oriented and connectionless sockets. Connection TCP, providing socket type is SOCK_STREAM, connectionless With UDP, a socket type SOCK_DGRAM.


simple socket of C / S

When socketserver now generally used to develop, but I'm a beginner so I decided to write some simple scripts to start learning from the socket.

First with the basic communication socket's simulate C / S Construction. The first is server-side, of course, divided into TCP and UDP server, TCP first to practice. As a TCP server, we must first wait for a connection from the client. And then establish a connection to the client, and finally the client to communicate. socket have many attributes, listed here are several common attributes, which is why we need the property.

socket(family,type,proto) address family is family, we use AF_INET, of course, which is the default, type we use SOCK_STREAM, which is the default, the last being less than a proto argument, is not considered.

bind(address)The method used to bind the server side ipand portit only takes one parameter, so you need to ipand portpackaged as a tuple to pass.

listen()The method to start the server starts listening

accept()The method waits for a connection request of a client, if the client requests a connection, the method generates a connection object, and the object and the client ipreturned as the return value. When the connection object is created, the server and the client can start the interaction. Of course, when the accept()After creating an object, it will return to its original state to wait for a new connection, will repeat the process when the arrival of a new connection.

recv(buffer)The method for receiving data bufferis the size of the received data. Of course, the type of data tobytes

send(bytes) Also send data, sendbytes

For so many precedents, began the first program below, life needs a sense of ritual, from the name of a NB Binary_TCPserver_V1

# Binary_TCPserver_V1
import socket
from time import ctime
server = socket.socket()
server.bind(("localhost",6969))
server.listen()  # starting listen
print('waiting connection...')
conn,addr = server.accept()  # wait the connect in ...
                # and return a connection representing and a ip address
data = conn.recv(1024)
print("Server recive data:",data)
conn.send(b'[%s] %s'% (data,ctime().encode('utf-8')))   
# send a bytes type not a str
server.close()

We receive a set of data from the client, and then return the data plus the current time, it is clear that this is not a qualified server program that takes complete a connection request once and client interaction after the exit, and the server is not supposed to exit. But in order to try the program logic is correct, write a simple client to interact with it a bit.

# Binary_TCPclinet_V1
import socket
clinet = socket.socket()
clinet.connect(('localhost',6969))
send_data = input('>>:')   # type is string
clinet.send(send_data.encode('utf-8'))    # change type to bytes
data = clinet.recv(1024)   #  buffersize 1024 Byte
print("Clinet recive data:",data.decode())
clinet.close()

To run the server, and then run the client, the client returns

>>:i am binary
Clinet recive data: [i am binary] Mon Dec  9 17:06:41 2019

The server returns

waiting connection...
Server recive data: b'i am binary'

See that we have achieved a simple interaction, however, the client can not say a word returned from the server and then ended the conversation now. We want the server has been running down, the client said enough and then quit and not say it out of connections. onBinary_TCPserver_V2

while True:
    print('waiting connection...')
    conn,addr = server.accept()  # wait the connect in ...
                    # and return a connection representing and a ip address
    while True:
        data = conn.recv(1024)
        if not data:
            print('clinet has broken the connection...')
            break
        print("Server recive data:",data)
        conn.send(b'[%s] %s'% (data,ctime().encode('utf-8')))   # send a bytes type not a str
server.close()

In fact, it is the addition of two cycles, client code, a kind of interactive fill.

# Binary_TCPclinet_V1
import socket
clinet = socket.socket()
clinet.connect(('localhost',6969))
while True:
    send_data = input('>>:')   # type is string
    if not send_data:
        break
    clinet.send(send_data.encode('utf-8'))    # change type to bytes
    data = clinet.recv(1024)   #  buffersize 1024 Byte
    print("Clinet recive data:",data.decode())
clinet.close()

Test, the client

>>:i am binary
Clinet recive data: [i am binary] Mon Dec  9 18:15:50 2019
>>:i am handsome
Clinet recive data: [i am handsome] Mon Dec  9 18:15:58 2019
>>:

Service-Terminal

waiting connection...
Server recive data: b'i am binary'
Server recive data: b'i am handsome'
clinet has broken the connection...
waiting connection...

We see that we have basically a single-threaded server, and this is certainly not the ultimate goal. With this foundation, not too tangled there are a lot of content on the socket will not. We began to enter socketserverthis is the ultimate goal.

url: SocketServer I'm coming (chicken dish learning ...)

url: Some interesting socket on small chestnuts

Guess you like

Origin www.cnblogs.com/planBinary/p/12013018.html