Python study notes --Day07

Python study notes --Day07

The seventh day, to see network programming relevant today. Two days ago because of their work, delayed blog updates.

Use the socket

socket (referred socket) is a way of inter-process communication, its relations with other processes to communicate is a major difference: it can achieve inter-process communication between different hosts on our network to complete a lot of services are based on Socket communication.

Socket module used in Python socket can function

import socket
socket.socket(AddressFamily,Type)

First socket.socket create a socket, this function takes two parameters:

  • Address Family: you can choose AF_INET (Internet for inter-process communication) or AF_UNIX (for inter-process communication on the same machine), commonly used in the work is AF_INET
  • TYPE: socket type may be SOCK_STREAM (stream sockets, primarily for the TCP protocol) or SOCK_DGRAM (datagram socket, primarily for UDP protocol)

For example, if I create a tcp socket, so write

import socket

# 创建tcp的套接字
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 功能代码 略...
...

# 当逻辑结束后,关闭socket
s.close()

Udp socket to create a socket, then only need to approach the second parameter, replaced socket.SOCK_DGREAM

import socket

# 创建udp的套接字
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 功能代码 略...
...

# 当逻辑结束后,关闭socket
s.close()

It simply is the process using sockets

  1. Create socket
  2. Using sockets for receiving / transmitting data
  3. Closes the socket

Is not it a bit familiar? The fourth day of file operations and this process is somewhat similar, open files, manipulate files, and then call close () method to close, then I just wrote a small example, tomorrow Sunday detailed summary of a document related to the operation content.

Create udp transmission / reception data

Simple transmission and reception procedures socket

Receiving the code loop

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:socket接收
import socket


def main():
    # 创建udp socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 绑定端口
    local_addr = ("127.0.0.1", 8080)
    s.bind(local_addr)

    # 循环接收
    while True:

        # 接收数据,返回的是一个元组(接收到的数据,(发送方的地址信息))
        recv_message = s.recvfrom(1024)
        recv_data = recv_message[0]
        recv_address = recv_message[1]
        # 打印结果
        print("从%s接收:%s" % (recv_address, recv_data.decode("utf-8")))
        # 如果接收的是quit
        if recv_data.decode("utf-8") == 'quit':
        	print("接收程序退出")
            break
    s.close()


if __name__ == "__main__":
    main()

Code transmission loop

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:udp socket 发送
import socket


def main():
    # 创建udp socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    while True:
        # 键盘录入要发送的数据
        send_data = input("请输入要发送的数据:")

        # 发送数据,
        send_addr = ("127.0.0.1", 8080)
        s.sendto(send_data.encode("utf-8"), send_addr)
        # 若输入quit 退出程序
        if send_data == "quit":
            print("发送程序退出")
            break
    s.close()


if __name__ == "__main__":
    main()

Result of the program

发送程序

请输入要发送的数据:你好
请输入要发送的数据:quit
发送程序退出
接收程序

从('127.0.0.1', 62189)接收:你好
从('127.0.0.1', 62189)接收:quit
接收程序退出

Process or set of processes, creates a socket, send and receive data using a socket, the socket is closed, but added an infinite loop, enter quit to exit the program at the time, it is necessary to note that the string is encoded and bytecode is decoded, use str.encode(encoding="utf-8", errors="strict")``bytes.decode(encoding="utf-8", errors="strict"), wherein the encoding means encoding used in encoding and decoding process, for example I use a utf-8, errors refers error handling scheme. Specific reference may be official documents. There is udp receive and transmit processes have something different, multi-step reception socket.bind()parameters passed a tuple is a tuple ip and port, in fact, can not bind the port, but in this case the operating system randomly port assignments, when the re-run program may send changes in port, but as a server-side program, the port is always changing, then the client we need to change the port every day, that's what we do this step port binding purposes .

Case -udp chat room

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:udp 聊天室
import socket


def send_msg(s):
    send_ip = input("请输入要发送的IP地址:")
    send_port = int(input("请输入要发送的端口号:").strip())
    send_message = input("请输入要发送的信息:")
    s.sendto(send_message.encode("utf-8"), (send_ip, send_port))


def recv_msg(s):
    recv_message = s.recvfrom(1024)
    recv_data = recv_message[0].decode("utf-8")
    recv_addr = recv_message[1][0] + ": " + str(recv_message[1][1])
    print("从%s接收消息:%s" % (recv_addr, recv_data))


def main():
    # 创建udp socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(("", 8080))
    while True:
        print("欢迎进入聊天室")
        print("1.发送消息")
        print("2.接收消息")
        print("0.退出聊天室")
        op = input("请输入操作:")
        if op == "1":
            # 发送
            send_msg(s)
        elif op == "2":
            # 接收
            recv_msg(s)
        elif op == "0":
            print("退出聊天室")
            break
        else:
            print("输入有误,请重新输入。")
    s.close()


if __name__ == "__main__":
    main()

Sent to their output

欢迎进入聊天室
1.发送消息
2.接收消息
0.退出聊天室
请输入操作:1
请输入要发送的IP地址:127.0.0.1
请输入要发送的端口号:8080
请输入要发送的信息:haha
欢迎进入聊天室
1.发送消息
2.接收消息
0.退出聊天室
请输入操作:2
从127.0.0.1: 8080接收消息:haha
欢迎进入聊天室
1.发送消息
2.接收消息
0.退出聊天室
请输入操作:0
退出聊天室

So our little chat room is complete! But this little chat rooms have a very serious problem, if you know, please give me a reply later in the article, I will answer revealed the next blog post

TCP sockets

TCP sockets TCP protocol is to use the transport service provided by the programming interface to implement network communications. To the second socket only parameter setting method SOCK.STREAM can get a TCP socket. Due to a host may have multiple IP addresses, and is likely to configure a number of different services, so as a server, you need to create a socket object after it is bound to the specified IP address and port.
Let's look at the server and client

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:tcp 套接字服务器端
import socket


def main():
    # 创建tcp套接字
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定端口
    s.bind(("127.0.0.1", 8080))
    # socket创建的套接字默认属性是为主动的
    # 将套接字的属性变为被动,接收发送来的数据
    s.listen(1024)
    # 当有客户端连接到服务器时,就产生一个新的套接字专门来为这个客户端服务
    # client_socket 为这个客户端服务的套接字
    # 而s则继续等待其他客户端连接
    client_socket, client_addr = s.accept()
    # 接收数据
    recv_data = client_socket.recv(1024)
    print("从%s接收到的数据为:%s" % (client_addr, recv_data.decode("utf-8")))
    # 返回数据到客户端
    client_socket.send("收到啦!".encode("utf-8"))
    # 关闭服务于这个客户端的套接字,关闭后,就意味着只能重新连接才能再次开启服务
    client_socket.close()


if __name__ == "__main__":
    main()

Client

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:tcp 套接字客户端
import socket


def main():
    # 创建tcp套接字
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 连接服务器
    s.connect(("127.0.0.1", 8080))
    # 发送数据
    send_msg = input("请输入要发送的信息:")
    s.send(send_msg.encode("utf-8"))
    # 接收数据
    recv_data = s.recv(1024)
    print("从服务器接收到的数据为:%s" % recv_data.decode("utf-8"))
    # 关闭套接字
    s.close()


if __name__ == "__main__":
    main()

Endless loop may be added on the server side, the message receiving cycle. Not discussed here. have to be aware of is

  • tcp server needs to bind, otherwise the client can not connect server
  • tcp client is generally not binding, because the initiative is linked server, so just make sure good server ip, port and other information like the local client can randomly
  • tcp listen socket server through socket can be created out of the initiative will become a passive, this must be done when doing tcp servers
  • When a client needs linked server, you need to connect link, udp is but need not be linked directly, but must be tcp link, only a link to the success of communication
  • When a client tcp connect to the server, the server will be a new socket, the socket used to mark the client, the client service is individually
  • After the passive socket listen socket for receiving the new client link request, and returns the new socket accept this new client marker
  • After the close listen sockets mean passive socket is closed, and will lead to a new client is not able to link servers, but has been previously linked the success of the client communicate properly.
  • Close accept the return of the socket means that the client has completed service
  • When close client socket call, recv server will clog solution, and the returned length is zero, so the server can be discriminated whether or not the client has the length of data returned by the offline

Epilogue

About this socket programming is over.
If you find my articles where there is an error or have any good ideas can contact me, we study together progress together, my email address is [email protected]

let’s do more of those!

Published 26 original articles · won praise 2 · Views 2340

Guess you like

Origin blog.csdn.net/qq_42909545/article/details/103180813