TCP客户端、服务端
代码
import socket
target_host = "127.0.0.1"
target_port = 9999
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host, target_port))
client.send("GET / HTTP/1.1\r\nHost: baidu.com\r\n\r\n")
response = client.recv(4096)
print response
利用NetAssist 模拟客户端发送接收回复的过程。
1.打开NetAssist,设置为TCP Server,点击打开
2.客户端设置好ip端口,运行,发送消息
接收消息成功
3.服务端回复消息,客户端接收成功。
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()
UDP客户端、服务端
客户端代码
import socket
target_host = "127.0.0.1"
target_port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto("AABBBCCC",(target_host, target_port))
data, addr = client.recvfrom(4096)
print data
服务端代码
import socket
target_host = ""
target_port = 8888
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind((target_host, target_port))
while True:
recv_data = udp_socket.recvfrom(1024)
print "[%s]:%s" % (str(recv_data[1]),recv_data[0].decode("gb2312"))
测试,python服务端,NetAssist作客户端或者自己编写的python代码作客户端
参考链接:
https://zhuanlan.zhihu.com/p/29598584
|