基于udp实现套接字通信、基于socketserver实现并发(udp和tcp)

一、基于udp实现套接字通信

 

服务端:

from socket import *

server = socket(AF_INET, SOCK_DGRAM)
server.bind(('127.0.0.1', 8080))

while True:
data, client_addr = server.recvfrom(1024)
print('====>',data,client_addr)
server.sendto(data.upper(), client_addr)

server.close()

客户端:
from socket import *
client=socket(AF_INET,SOCK_DGRAM)#数据报协议-》udp

while True:
msg=input('>>:').strip() #msg='' 空数据也可以发送(其实不是空数据,每个数据都有报头,udp不会发送空数据)
client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
data,server_client=client.recvfrom(1024)
print(data)
client.close()



#udp协议没有粘包问题,不能用来传大的数据 每次传送最好不大于512字节


二、基于socketserver实现并发(udp和tcp)

服务端(tcp):
import socketserver

class MyHandler(socketserver.BaseRequestHandler):
def handle(self):
#通信循环
while True:
# print(self.client_address)
# print(self.request) #self.request=conn

try:
data=self.request.recv(1024)
if len(data) == 0:break
self.request.send(data.upper())
except ConnectionResetError:
break

if __name__ == '__main__':
s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyHandler,bind_and_activate=True)

s.serve_forever() # 代表连接循环
# 循环建立连接,每建立一个连接就会启动一个线程(服务员)+调用Myhanlder类产生一个对象,
# 调用该对象下的handle方法,专门与刚刚建立好的连接做通信循

客户端(tcp):

import socket

phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080)) # 指定服务端ip和端口

while True:
msg=input('>>: ').strip() #msg=''
# msg = 'client22222' # msg=''
if len(msg) == 0:continue
phone.send(msg.encode('utf-8'))
data=phone.recv(1024)
print(data)

phone.close()



服务端(udp):
import socketserver

class MyHandler(socketserver.BaseRequestHandler):
def handle(self):
#通信循环
# print(self.client_address)
# print(self.request)

data=self.request[0]
print('客户消息',data)
self.request[1].sendto(data.upper(),self.client_address)


if __name__ == '__main__':
s=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyHandler)
s.serve_forever()

客户端(udp):
import socket

client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #数据报协议-》udp

while True:
msg=input('>>: ').strip() #msg=''
# msg='client444444'

client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
data,server_addr=client.recvfrom(1024)
print(data)

client.close()





posted @ 2018-07-11 18:47  Shinonon  阅读(206)  评论(0编辑  收藏  举报