服务器端:
- 创建服务器的socket对象
- 监听ip和端口号
- 设置最大连接数
- 创建一个客服处理线程:接收客户端发来的数据,再向客户端发送数据
- 开启线程,等待客户连接。
import socket
import threading
bind_ip = "0.0.0.0"
bind_port = 51112
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
print("[*] Listening on %s:%d" % (bind_ip,bind_port))
server.listen(5)
def handle_client(client_socket):
request = client_socket.recv(1024)
print("[*] Received: %s" % request)
client_socket.send("hi~".encode())
client_socket.close()
while True:
client,addr = server.accept()
print("[*] Acception connection from %s:%d" % (addr[0],addr[1]))
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()
客户端:
- 创建客户端socket对象
- 用socket对象连接到服务器端(target_host, target_port是服务器端的ip与端口)
- 向服务器端发送数据
- 从服务器端接收数据
import socket
target_host = "127.0.0.1"
target_port = 51112
while True:
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((target_host,target_port))
data = input(">")
if not data:
break
client.send(data.encode())
response = client.recv(1024)
print(response)
client.close()