文章目录
TCP客户端、服务端
代码
# -- coding: utf-8
# 开始一直报错,发现是文件夹命名中文的问题
import socket
target_host = "127.0.0.1"
target_port = 9999
# 建立一个socket对象
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服务端
代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Autor:tangzicheng
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客户端、服务端
客户端代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Autor:tangzicheng
import socket
target_host = "127.0.0.1"
target_port = 80
# 建立一个socket对象
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据
client.sendto("AABBBCCC",(target_host, target_port))
# 接收数据
data, addr = client.recvfrom(4096)
print data
服务端代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Autor:tangzicheng
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代码作客户端