tcp udp测试
sub_udp.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 可以正常接收udp
import socket
import datetime
#创建socket对象
#SOCK_DGRAM udp模式
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('', 10000))
while True:
# data = s.recv(10240)
data = s.recv(102400)
print("开始收到下面一条udp" + ' 当前时间: ' + str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
print(data.decode())
--------------------------------------------------------------------------------------------------------------------
pub_udp.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 可以正常发送udp
# 可以正常发送udp
#不需要建立连接
import socket
import time
#创建socket对象
#SOCK_DGRAM udp模式
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#发送数据 字节
str1 = {"name":"mark", "age":18, "content":"meeting"}
while True:
s.sendto(str(str1).encode(), ('127.0.0.1', 10000))
time.sleep(1)
--------------------------------------------------------------------------------------------------------------------
sub_tcp.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 可以正常跑通
import socket
import time
MaxBytes = 1024 * 1024
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.settimeout(60)
host = '127.0.0.1'
# host = socket.gethostname()
port = 11223
server.bind((host, port)) # 绑定端口
server.listen(1) # 监听
try:
client, addr = server.accept() # 等待客户端连接
print(addr, " 连接上了")
while True:
data = client.recv(MaxBytes)
if not data:
print('数据为空,我要退出了')
break
localTime = time.asctime(time.localtime(time.time()))
print(localTime, ' 接收到数据字节数:', len(data))
print(data.decode())
client.send(data)
except BaseException as e:
print("出现异常:")
print(repr(e))
finally:
server.close() # 关闭连接
print("我已经退出了,后会无期")
--------------------------------------------------------------------------------------------------------------------
pub_tcp.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 可以正常跑通
import socket
import time
MaxBytes=1024*1024
host ='127.0.0.1'
port = 11223
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.settimeout(30)
client.connect((host,port))
while True:
inputData = "hello world!"; #等待输入数据
sendBytes = client.send(inputData.encode())
if sendBytes<=0:
break;
recvData = client.recv(MaxBytes)
if not recvData:
print('接收数据为空,我要退出了')
break
localTime = time.asctime( time.localtime(time.time()))
print(localTime, ' 接收到数据字节数:',len(recvData))
print(recvData.decode())
client.close()
print("我已经退出了,后会无期")