socket tcpudp案例

Posted lides

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket tcpudp案例相关的知识,希望对你有一定的参考价值。


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 tcpudp案例的主要内容,如果未能解决你的问题,请参考以下文章

socket编程TCPUDP通信总结

socket编程TCPUDP通信总结

socket之tcpudp

socket编程TCPUDP通信你会了吗?

socket编程TCPUDP通信你会了吗?

Socket网络编程TCPUDP演示样例