TCPServer端:
__author__ = 'Nature'
# -*- coding: utf-8 -*-
from socket import *
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ=1024
ADDR = (HOST,PORT)
tcpserver = socket(AF_INET,SOCK_STREAM)
tcpserver.bind(ADDR)
tcpserver.listen(5)
while True:
print("waiting for connection....")
tcpclient ,addr = tcpserver.accept()
print('...connected from:',addr)
while True:
data = tcpclient.recv(BUFSIZ)
if not data:
break
tcpclient.send(('[%s]%s'%(ctime(),data)).encode())
tcpclient.close()
tcpserver.close()
TCPclient端:
__author__ = 'Nature'
# -*- coding: utf-8 -*-
from socket import *
HOST ='127.0.0.1'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
tcpclient = socket(AF_INET,SOCK_STREAM)
tcpclient.connect(ADDR)
while True:
data = input('>')
if not data:
break
tcpclient.send(data.encode())
data = tcpclient.recv(BUFSIZE)
if not data:
break
print(data)
tcpclient.close()
UDPserver端:
__author__ = 'Nature'
# -*- coding: utf-8 -*-
from socket import *
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ=1024
ADDR = (HOST,PORT)
tcpserver = socket(AF_INET,SOCK_DGRAM)
tcpserver.bind(ADDR)
while True:
print("waiting for message....")
tcpclient ,addr = tcpserver.recvfrom(BUFSIZ)
tcpserver.sendto(('[%s]%s'%(ctime(),tcpclient)).encode(),addr)
print('...receive from and returned to:',addr)
tcpserver.close()
UDPclient端:
__author__ = 'Nature'
# -*- coding: utf-8 -*-
from socket import *
HOST ='127.0.0.1'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
udpclient = socket(AF_INET,SOCK_DGRAM)
while True:
data = input('>')
if not data:
break
udpclient.sendto(data.encode(),ADDR)
data,ADDR = udpclient.recvfrom(BUFSIZE)
if not data:
break
print(data)
udpclient.close()