Python's network programming socket

Source: Internet
Author: User

(1) simple link with socket

the socket inside Python supports UDP, TCP, and interprocess communication . the socket can encapsulate what we want to send, send the past, and then back to the original appearance, in fact, network communication can understand that Chengdu is built on the socket, the following code is to demonstrate the use of the socket for simple links

#要成一次通信, at least two people, that is, a server, a client # server "must be open, waiting for the client to make a link request, so you have to first have an address, that is, IP, also have their own port, no port into the" import socketsk= Socket.socket () #创建对象sk. Bind ((' 127.0.0.1 ', 9999,)) #绑定IP和端口, passed in a tuple sk.listen (5) #在前面链接已经建立的情况下, with up to five people waiting in the back while True: #让服务器端处于可以永远处于接受客户端请求的状态    conn,address=sk.accept ()    print (conn,address) "Listening port, waiting and accepting requests from clients, may block, The main function is to establish a link, and to accept the client information Conn equivalent to the establishment of this link, and then communicate with each other to rely on this link; address refers to the other side of the IP and port "

Here is the client code

#客户端import socketobj =socket.socket () ' relative to the client, make a link to who will be Good ' obj.connect ((' 127.0.0.1 ', 9999,)) #链接服务端obj. Close () # Close after link

Let's start the server and then start the client, and the result

Successfully print out each link, as well as the client's IP and port number

(2) Simple message transmission based on socket

#服务器端import socketsk= Socket.socket () sk.bind (' 127.0.0.1 ', 9999,) #绑定IP和端口, passed in a tuple sk.listen (5) #在前面链接已经建立的情况下, A maximum of five people to wait while True: #让服务器端处于可以永远处于接受客户端请求的状态    conn,address=sk.accept () #基于conn这个链接发送东西    Conn.sendall ( Bytes (' Someday you'll be a Python crawler engineer ', encoding= ' Utf-8 ')) #Python3要用bytes类型, send Byte ' ' to    create a link, the server sends this field ' ' Print '    ( conn,address)

Then use the client-side code

#客户端import socketobj =socket.socket () "' relative to the client, make a link to who will be Good ' obj.connect ((' 127.0.0.1 ', 9999,)) #链接服务端 ' ' Client to link to the server, If the server does not return a message to the client, the client will remain in the recv state, waiting for the server's message ' result1= obj.recv #表示最多接收1024个字节, exceeding the next receive, result2= str (RESULT1, encoding= ' Utf-8 ') print (RESULT2) obj.close () #链接之后关闭

When the client is started once to establish a link, the message is received and the result

(3) Implement the chat robot based on socket

#服务器端import socketsk= Socket.socket () sk.bind (' 127.0.0.1 ', 9999,) #绑定IP和端口, passed in a tuple sk.listen (5) #在前面链接已经建立的情况下, A maximum of five people to wait while True: #让服务器端处于可以永远处于接受客户端请求的状态    conn,address=sk.accept () #基于conn这个链接发送东西    Conn.sendall ( Bytes (' Hello, link already established ', encoding= ' Utf-8 ')) #Python3要用bytes类型, send byte    # ' to establish a link, the server will first send this field ' while    true:# Make communication state uninterrupted        ret_bytes = Conn.recv (1024x768)        ret_str = str (ret_bytes,encoding= ' utf-8 ')        if ret_str = = ' Q ': #如果收到q, Then terminate the link break        conn.sendall (bytes (ret_str+ ' has received this information ', encoding= ' Utf-8 '))    #print (conn,address)

Here is the client code

#客户端import socketobj =socket.socket () "' relative to the client, make a link to who will be Good ' obj.connect ((' 127.0.0.1 ', 9999,)) #链接服务端 ' ' Client to link to the server, If the server does not return a message to the client, the client will remain in the recv state, waiting for the server's message ' result1= obj.recv #表示最多接收1024个字节, exceeding the next receive, result2= str (RESULT1, encoding= ' Utf-8 ') print (RESULT2) while True:    data = input (' Please enter what you want to send: ')    if data = = ' Q ':        obj.sendall (bytes (Data, encoding= ' Utf-8 '))        Print (' link broken ')        break    Else:        obj.sendall (bytes (data,encoding= ' utf-8 '))        rec_byte = OBJ.RECV (1024) # After sending, receive message        REC_STR = str (rec_byte,encoding= ' utf-8 ')        print (REC_STR) obj.close () #链接之后关闭

Results

Python's network programming socket

Related Article

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.