码迷,mamicode.com
首页 > 其他好文 > 详细

socket tcp、udp案例

时间:2019-07-11 17:25:22      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:import   客户   ddr   bind   encode   div   bin   客户端   ram   


udp_client

from socket import *

client_addr = (127.0.0.1,8000)

udp_client = socket(AF_INET,SOCK_DGRAM)

while True:
    msg = input(==>)
    udp_client.sendto(msg.encode(utf8),client_addr)
    data,client_addr = udp_client.recvfrom(1024)
    print(服户端%s:%s %(client_addr,str(data,utf8)))

 


udp_server
from socket import *

server_addr = (127.0.0.1,8000)

udp_server = socket(AF_INET,SOCK_DGRAM)
udp_server.bind(server_addr)
while True:
    data,client_addr = udp_server.recvfrom(1024)
    print(客户端%s:%s %(client_addr,str(data,utf8)))
    udp_server.sendto(str(data,utf8).upper().encode(utf8),client_addr)

tcp_server

from socket import *

‘‘‘
socket.AF_INET 指定为网络套接字
OCK_STREAM 指定传输协议为tcp
‘‘‘
server_addr=(127.0.0.1,8000)
backlog=10
buffersize=1024

tcp_server = socket(AF_INET,SOCK_STREAM)
tcp_server.bind(server_addr)
tcp_server.listen(backlog)
conn,addr_client = tcp_server.accept()
msg = conn.recv(buffersize)
conn.send(str(msg,utf8).upper().encode(utf8))
print(客户端消息:%s % str(msg,utf8))

tcp_client

from socket import *

client_addr=(127.0.0.1,8000)

phone = socket(AF_INET,SOCK_STREAM)
phone.connect(client_addr)
msg = input(>>:)
phone.send(msg.encode(utf8))
reply = phone.recv(1024)
print(服务端消息:%s % str(reply,utf8))

 



socket tcp、udp案例

标签:import   客户   ddr   bind   encode   div   bin   客户端   ram   

原文地址:https://www.cnblogs.com/lides/p/11170916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!