####UDP初试
##服务端
import socket
server = socket.socket(type=socket.SOCK_DGRAM)
server.bind(('127.0.0.1',8080))
while True:
data, addr = server.recvfrom(1024)
print(data.decode('utf-8'))
server.sendto(data.upper(),addr)
##客户端
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
server_addr = ('127.0.0.1',8080)
while True:
# msg = input('>>>:')
# msg = '客户端1:%s'%msg
# client.sendto(msg.encode('utf-8'),server_addr)
client.sendto(b'hello',server_addr)
data,addr = client.recvfrom(1024)
print(data)
##TCP服务端
import socketserver
class MyBaby(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
data = self.request.recv(1024)
print(data)
self.request.send(data.upper())
except ConnectionResetError:
break
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyBaby)
server.serve_forever()
# UDP 服务端
#socketserver使用
import socketserver
class MyUdpServer(socketserver.BaseRequestHandler):
def handle(self):
while True:
data, sock = self.request
print(data)
sock.sendto(data.upper(), self.client_address)
if __name__ == '__main__':
server = socketserver.ThreadingUDPServer(('127.0.0.1', 8080), MyUdpServer)
server.serve_forever()
#客户端
import socket
import time
client = socket.socket()
client.connect(('127.0.0.1',8080))
while True:
client.send(b'hello')
data = client.recv(1024)
print(data)
time.sleep(1)