python--Network Programming-----Socket Programming Example--call--plus link loop

Source: Internet
Author: User

One, code example

Service side:

1 ImportSocket2 3 4Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)5Phone.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)6Phone.bind (('127.0.0.1', 8080))#0-65535:0-1024 for operating system use7Phone.listen (5)8 9 Print('starting .....')Ten  whileTrue:#Link Loops Oneconn, client_addr =phone.accept () A     Print(CLIENT_ADDR) -  -      whileTrue:#Communication Cycle the         Try: -data = CONN.RECV (1024) -             if  notData#for Linux operating systems -                  Break +             Print('client-side data', data) -  + Conn.send (Data.upper ()) A         exceptConnectionreseterror:#for Windows operating systems at              Break -  - conn.close () -  -Phone.close ()

Client 1

1 ImportSocket2 3 #1. Buy Mobile phone4Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)5 #print (phone)6 7 #2. Dialing8Phone.connect (('127.0.0.1', 8080))9 Ten #3. Send and receive Messages One  whileTrue: Amsg = input ('>>:'). Strip () -     if  notmsg: -         Continue thePhone.send (Msg.encode ('Utf-8')) -data = PHONE.RECV (1024) -     Print(data) -  + #4. Close -Phone.close ()

Client 2

1 ImportSocket2 3 #1. Buy Mobile phone4Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)5 #print (phone)6 7 #2. Dialing8Phone.connect (('127.0.0.1', 8080))9 Ten #3. Send and receive Messages One  whileTrue: Amsg = input ('>>:'). Strip () -     if  notmsg: -         Continue thePhone.send (Msg.encode ('Utf-8')) -data = PHONE.RECV (1024) -     Print(data) -  + #4. Close -Phone.close ()

After the link loop, the server can provide services to client 1 and client 2 in turn, but can serve only one client and cannot provide services in parallel

python--Network Programming-----Socket Programming Example--call--plus link loop

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.