码迷,mamicode.com
首页 > 编程语言 > 详细

Python之路——网络编程

时间:2018-01-29 16:19:34      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:rom   enc   客户端   repr   span   ble   res   blog   color   

socket

TCP

服务端

 1 import socket
 2 sk = socket.socket()
 3 sk.bind((127.0.0.1,8080)) # 绑定ip和端口号
 4 sk.listen() # Enable a server to accept connections.
 5 conn,addr = sk.accept() # Wait for an incoming connection.  Return a new socket
 6                         # representing the connection, and the address of the client.
 7 while 1:
 8     content = conn.recv(1024)   # 接收
 9     print(content.decode(utf-8))
10     conn.send(content+b--liuyankui)   # 发送
11 conn.close()
12 sk.close()

客户端

1 import socket
2 sk = socket.socket()
3 sk.connect((127.0.0.1,8080))  #连接
4 while 1:
5     content = input(>>>).encode(utf-8)
6     sk.send(content)
7     ret = sk.recv(1024)
8     print(ret.decode(utf-8))
9 sk.close()

 

UDP

服务端

1 import socket
2 sk = socket.socket(type=socket.SOCK_DGRAM)
3 sk.bind((127.0.0.1,8080))
4 msg ,addr = sk.recvfrom(1024)
5 print(msg.decode(utf-8))
6 sk.sendto(bbye,addr)
7 sk.close()

用户端

1 import socket
2 sk = socket.socket(type=socket.SOCK_DGRAM)
3 ip_port = (127.0.0.1,8080)
4 sk.sendto(bhello,ip_port)
5 msg,addr = sk.recvfrom(1024)
6 print(msg.decode(utf-8))
7 sk.close()

 

Python之路——网络编程

标签:rom   enc   客户端   repr   span   ble   res   blog   color   

原文地址:https://www.cnblogs.com/liuyankui163/p/8351682.html

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