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