python网络编程简介

1.  TCP客户端

 1 # coding:utf8
 2 
 3 import socket
 4 
 5 target_host = 'www.chengzhier.com'
 6 target_port = 80
 7 
 8 # 建立一个socket 对象 
 9 # socket.AF_INET表示IPv4地址,或者主机名
10 # socket.SCOK_STREAM 这将是一个TCP客户端
11 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
12 
13 # 连接客户端
14 client.connect((target_host, target_port))
15 
16 # 发送一些数据
17 client.send("GET / HTTP/1.1
Host: chengzhier.com

")
18 
19 # 接收一些数据
20 response = client.recv(4096)
21 
22 print response

 2. UDP客户端

 1 # coding:utf8
 2 
 3 import socket
 4 
 5 target_host = '127.0.0.1'
 6 target_port = 80
 7 
 8 # 建立一个socket 对象 
 9 # socket.AF_INET表示IPv4地址,或者主机名
10 # socket.SCOK_DGRAM 这将是一个UDP客户端
11 client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
12 
13 
14 # 发送一些数据
15 client.sendto("AABBCC", (target_host, target_port))
16 
17 # 接收一些数据
18 # 这里老是报出 socket error 10054  应该是本地的防火墙的问题
19 data, addr = client.recvfrom(4096)
20 
21 print data

 3. TCP服务器端

 1 # coding:utf8
 2 import socket
 3 import threading
 4 
 5 bind_ip = "0.0.0.0"
 6 bind_port = 9999
 7 
 8 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 9 
10 server.bind((bind_ip, bind_port))
11 
12 server.listen(5)
13 
14 print "[*] Listening on %s:%d " % (bind_ip, bind_port)
15 
16 # 这是客户处理线程
17 def handle_client(client_socket):
18 
19     # 打印出客户端发送得到内容
20     request = client_socket.recv(1024)
21 
22     print "[*] Received: %s" % request
23 
24     # 返还一个数据包
25     client_socket.send("ACK!")
26 
27     client_socket.close()
28 
29 while True:
30     
31     client, addr = server.accept()
32     print "[*] Accepted connection from: %s:%d" % (addr[0], addr[1])
33 
34     # 挂起客户端,处理传入的数据
35     client_handler = threading.Thread(target=handle_client, args=(client,))
36 
37     client_handler.start()

然后在用tcp客户端 访问,就可以了,代码

 1 # coding:utf8
 2 
 3 import socket
 4 
 5 target_host = '127.0.0.1'
 6 target_port = 9999
 7 
 8 # 建立一个socket 对象 
 9 # socket.AF_INET表示IPv4地址,或者主机名
10 # socket.SCOK_STREAM 这将是一个TCP客户端
11 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
12 
13 # 连接客户端
14 client.connect((target_host, target_port))
15 
16 # 发送一些数据
17 client.send("GET / HTTP/1.1
Host: 127.0.0.1

")
18 
19 # 接收一些数据
20 response = client.recv(4096)
21 
22 print response

如果正常的话,客户端这边就会显示 ACK!, 服务器端就会显示发送过来的地址等信息。

原文地址:https://www.cnblogs.com/shaoshao/p/8716713.html