Python Learning notes (socket)

Source: Internet
Author: User

Build the service side

1. Import the module

Import socket

2. Create a Socket object

Sock=socket. Socket (socket_family,socket_topy)

3. Binding port

Sock.bind (("", 8000))

4. Setting Up Monitoring

Sock.listen (5)

5. Acceptance of information

Con,add=sock.accept ()

Con: Accept the Sock object, accept the message sent by the other party

ADD:IP recognition

Con.send ("Hello,i am Your Server")

6. Close the socket You

Sock.close ()

Setting up the socket TCP client

1. Import the module

Import socket

2. Create socket object, socket is a class

Sock=socket. Socket (socket_family,socket_topy)

3. Connect to the server

4. Acceptance of information

5. Close the socket

Sock.close () service-side code

#coding: UTF-8
#第一种, after sending hello on both sides of the link, respectively, disconnect
Import socket
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Sock.bind (("", 8000)) #绑定所有IP
Print "This is socket_server:127.0.0.1:8000"
Sock.listen (5)
Con,add=sock.accept ()
Print con
Print add
Print "%s is connected"%add[0]
Print CON.RECV (512)
Con.send ("Hello I am Your server")
Sock.close ()
#第二种, both sides of the text interaction
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Sock.bind ("127.0.0.1", 8000))
Sock.listen (5)
Con,add=sock.accept ()
While true:
RECVS=CON.RECV (512)
Print Recvs
If recvs== "Break":
Break
Sends=raw_input ("..")
Sock.send (Sends)
If sends== "Break":
Break
Sock.close ()

#第三种: Client sends break, server enters passive blocking accept
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Sock.bind ("127.0.0.1", 8000))
Sock.listen (5)
While true:
Con,add=sock.accept ()
While true:
RECVS=CON.RECV (512)
Print Recvs
If recvs== "Break":
Break
Sends=raw_input ("..")

Python Learning notes (socket)

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.