使用python的socket模块进行网络编程
使用socket编程可以分成基于tcp和基于udp,tcp和udp两者最主要的区别是有无面向连接。
基于tcp的socket流程:
基于udp的socket的流程图:
(以上两图来源于网络)
可以看到基于udp的socket要简单得多,udp的客户端不需要事先connect,而udp的服务器端也不需要listen和accept。
下面贴上一些tcp client, tcp server, udp client, udp server的简单实现代码
tcp client:
__author__ = 'seven' import socket target_host = "127.0.0.1" target_port = 80 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((target_host, target_port)) client.send("ABCDEF") response = client.recv(4096) print response
client.close()
tcp server:
__author__ = 'seven' import socket import threading bind_ip = "0.0.0.0" bind_port = 80 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip, bind_port)) server.listen(5) print "[*] Listening on %s:%d" % (bind_ip, bind_port) def handle_client(client_socket): request = client_socket.recv(1024) print "[*] Received: %s" % request client_socket.send("ACK!") client_socket.close() while True: client, addr = server.accept() print "[*] Accepted connection from: %s:%d" % (addr[0], addr[1]) client_handler = threading.Thread(target=handle_client, args=(client,)) client_handler.start()
server.close()
udp client:
__author__ = 'seven' import socket target_host = "127.0.0.1" target_port = 80 client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.sendto("ABCDEF", (target_host, target_port)) data, addr = client.recvfrom(4096) print data
client.close()
udp server:
__author__ = 'seven' import socket bind_ip = "0.0.0.0" bind_port = 80 server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind((bind_ip, bind_port)) while True: data, addr = server.recvfrom(4096) if not data: print "client has exist" break server.sendto("ACK!", addr) print "received:%s from %s" % (data, addr) server.close()
稍微解释一下一些参数:
AF_INET参数说明使用标准的IPv4地址或主机名
AF_INET6参数说明使用IPv6地址或主机名
SOCK_STREAM参数说明是一个TCP客户端
SOCK_DGRAM参数说明是一个UDP客户端
posted on 2015-09-10 17:16 7777777line 阅读(308) 评论(0) 编辑 收藏 举报