服务端
import socket
import threading
bind_ip = '127.0.0.1'
bind_port = 8888
# 绑定本地端口
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):
requests = client_socket.recv(1024)
print('[ * ] Received %s' % requests)
client_socket.send("Hiiiiiiiiiiiiiii".encode('utf-8'))
client_socket.close()
while True:
# accept()接受一个客户端的连接请求,并返回一个新的套接字,不同于socket()返回的用于监听和接受客户端的连接请求的套接字;与此客户端通信是通过这个新的套接字上发送和接收数据来完成的。
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()
客户端
import socket
target_host = '127.0.0.1'
target_port = 8888
# 建立一个socket对象(socket.AF_INET 使用标准的IPV4地址,socket.SOCK_STREAM 代表这是一个TCP客户端)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 链接客户端
client.connect((target_host, target_port))
# 发送请求
client.send('hello'.encode('utf-8'))
# 接收数据
response = client.recv(1024)
print(response)