Server-side
#-*-Coding:utf-8-*-
# python:2.x
__author__ = ' Administrator '
From socket Import *
From time Import *
Host= "
port=1122# Listening Port
bufsiz=1024
Addr= (Host,port)
Sock=socket (Af_inet,sock_stream)
Sock.bind (ADDR)
Sock.listen (5)
# Conditions
Stop_chat=false
While not stop_chat:
Print U ' waiting for access, listening port :%d ' (port)
Tcpclientsock,addr=sock.accept ()
Print U ' receive , client address :%d '% (addr)
While True:
Try
Data=tcpclientsock.recv (BUFSIZ) # receive data
Except
Tcpclientsock.close ()
Break
If not data:
Break
iostimeformat= '%y-%m-%d%x '
Strime=strftime (Iostimeformat,localtime ())
the message sent to me by S=u '%s is :%s '% (Addr[0],data.decode (' UTF8 '))
Tcpclientsock.send (S.encode (' UTF8 '))
Print ([Strime], ': ', Data.decode (' UTF8 '))
# If you enter quit ( ignoring case ), the program exits
stop_chat= (Data.decode (' UTF8 '). Upper () = = ' QUIT ')
If not stop_chat:
Break
Tcpclientsock.close ()
Sock.close ()
print '-------'
Client programs
#-*-Coding:utf-8-*-
# python:2.x
__author__ = ' Administrator '
From socket Import *
Class TcpC:
Host= ' 127.0.0.1 '
port=1122
bufsiz=2048
Addr= (Host,port)
def __init__ (self):
Self.client=socket (Af_inet,sock_stream)
Self.client.connect (self. ADDR)
While True:
Data=raw_input (' > ')
If not data:
Break
Self.client.send (data)
print ' send message to %s:%s '% (self. Host,data)
If data.upper () = = ' QUIT ':
Break
Data=self.client.recv (self. BUFSIZ)
If not data:
Break
print ' information received from %s '% (self. Host,data)
If __name__== ' __main__ ':
CLIENT=TCPC ()
print ' UDP learning '
# python:2.x
__author__ = ' Administrator '
From socket Import *
#upd Communications
port=8081# Port number
S=socket (af_inet,so_debug) # sender, receiving UDP data
S.bind (("', port)")
Print U ' waiting for data to be received '
While True:
# Receive Data
Data,addr=s.recvfrom ()
print ' Received: ', data, ' from: ', addr
#-*-Coding:utf-8-*-
# python:2.x
__author__ = ' Administrator '
From socket Import *
#upd Communications
port=8081# Port number
host= ' localhost '
S=socket (Af_inet,sock_dgram)
S.sendto (b ' hello,this is a Test info! ', (Host,port))
Python Socket Basic Learning, note that you need to open the server program, in the Open client program,