Python网络编程
TCP客户端

Import socket

target_host = “www.google.com”
target_port = 80

建立一个socket对象
Client = socket.socket(socket.AF_INEF,socket.SOCK_STREAM)

连接客户端
Client,client((target_host,target_port))

发送一些数据
Client.send(“GET / HTTP/1.1\r\nHost: google.com\r\n\r\n”)

接受一些数据
Response = client.recv(4096)

print response

UDP客户端
import socket

target_host = “127.0.0.1”
target_port = 80

建立一个socket用户
Client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

发送一些数据
client.sendto(“AAABBBCCC”,(target_host,target_port))

接受一些数据
data, addr = client.revfrom(4096)

Print data
TCP服务器

import socket
import threading
Bind_ip="0.0.0.0”
bind _port=9999
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()