Base On Socket
tcp
from socket import socket,AF_INET,SOCK_STREAM
def echo_server(address,backlog=5):
sock = socket(AF_INET,SOCK_STREAM)
sock.bind(address)
sock.listen(backlog)
while True:
client_sock,client_addr = sock.accept()
print('Got connection from {}'.format(address))
while True:
msg = client_sock.recv(8192)
if not msg:
print('The connection is closed')
break
client_sock.sendall(msg)
client_sock.close()
if __name__ == '__main__':
echo_server(('',20000))
from socket import socket,AF_INET,SOCK_STREAM
s = socket(AF_INET,SOCK_STREAM)
s.connect(('localhost',20000))
s.send(b'Hello.I am the client')
print(s.recv(8192))
s.close(
udp
from socket import SOCK_DGRAM,AF_INET,socket
def time_server(address):
sock = socket(AF_INET,SOCK_DGRAM)
sock.bind(address)
index = 0
while True:
msg,addr = sock.recvfrom(8192)
print('Got message from%s msg is:%s'%(addr,msg))
sock.sendto(str(index).encode(),addr)
index = index + 1
if __name__ == '__main__':
time_server(('',20000))
from socket import socket,AF_INET,SOCK_DGRAM
s = socket(AF_INET,SOCK_DGRAM)
s.sendto(b'Hello I am client',('localhost',20000))
print(s.recvfrom(8192))
|