Socket编程
1、介绍
python支持socket编程,可以使用TCP和UDP协议。同java中的socket编程相类似。
2、tcp协议
2.1 服务器端
服务器端绑定到指定地址,监听特定的端口,接受发来的连接请求。
# -*-coding:utf-8-*-
import socket
import threading
#接收者线程
class RecvThread(threading.Thread):
def run(self):
while True:
data = self.sock.recv(4096)
print "收到了%s:%d = %s" % (self.addr[0], self.addr[1], str(data)),
def __init__(self , sock , addr):
threading.Thread.__init__(self)
self.sock = sock
self.addr = addr
#创建socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#绑定socket地址
sock.bind(("127.0.0.1" , 8888))
sock.listen(0)
while True:
print "正在接收..."
client_sock ,addr = sock.accept()
print "%s:%d 连进来了!"%(addr[0] ,addr[1])
RecvThread(client_sock, addr).start()
2.2 客户端
# -*-coding:utf-8-*-
import socket
import time
# 创建socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务器
sock.connect(("127.0.0.1" , 8888))
i = 1
while True:
sock.send("tom" + str(i) + "\r\n")
print "sent : tom" +str(i)
i += 1
time.sleep(1)
3、UDP
3.1 发送端
# -*-coding:utf-8-*-
import thread
import time
import socket
if __name__ == '__main__':
#UDP协议
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#绑定到指定的地址和端口
sock.bind(("192.168.14.8" , 8888))
i = 1
while True:
#发送消息给广播地址
sock.sendto("tom" + str(i) , ("192.168.14.255" , 9999))
print "sent : tom" + str(i)
i += 1
time.sleep(1)
3.2 接收方
# -*-coding:utf-8-*-
import thread
import time
import socket
if __name__ == '__main__':
#UDP协议
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("192.168.14.8" , 9999))
while True:
data = sock.recv(4096)
print "收到消息 : %s"%(str(data))