Python---TCP/IP network programming

Source: Internet
Author: User

Key Summary:

Server: Running (while true), listening for a port on a running machine (IP), multi-threaded or multi-process receive client socket request

Client: Unsolicited request, need to know the IP and port of the server

Service side:

#-*-Coding:utf-8-*-
Import time
Import socket
Import threading
def tcplink (sock, addr):
Print' Accept new connection from%s:%s ... '% addr
Sock.send (' welcome! ')
WhileTrue:
data = SOCK.RECV (1024)
Time.sleep (1)
if data = =' Exit 'Or not data:
Break
Sock.send (' Hello,%s! '% data)
Sock.close ()
Print' Connection from%s:%s closed. '% addr


s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
S.bind ((' 127.0.0.1 ',9999))
S.listen (5)
Print' Waiting for connection ... '
While True:
# Accept a new connection:
Time.sleep (5)
print ' SDASDASD '
Sock, addr = S.accept ()
Print Sock
Print Addr
# Create a new thread to handle the TCP connection:
t = Threading. Thread (target=tcplink, args= (sock, addr))
T.start ()

Client:
#-*-Coding:utf-8-*-
Import time
Import socket
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
# to establish a connection:
S.connect ((9999))
# receive Welcome message:
1024)
for Data in [ Michael ', Tracy ', Sarah":
# send data:
S.send (data)
print s.recv (1024)
S.send ( ' exit ')
S.close ()
     

Python---TCP/IP network programming

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.