
上QQ阅读APP看书,第一时间看更新
Implementing the TCP serverIn this example, we are going to create a multithreaded TCP server.
The server socket opens a TCP socket on localhost:9999 and listens to requests in an infinite loop. When you receive a request from the client socket, it will return a message indicating that a connection has been made from another machine.
The while loop keeps the server program alive and does not allow the code to end. The server.listen(5) statement listens to the connection and waits for the client. This instruction tells the server to start listening with the maximum backlog of connections set to 5.
You can find the following code in the tcp_server.py file inside the tcp_client_server folder:
import socket
import threading
bind_ip = "localhost"
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)
# this is our client-handling thread
def handle_client(client_socket):
# print out what the client sends
request = client_socket.recv(1024)
print "[*] Received: %s" % request
# send back a packet
client_socket.send("Message received")
client_socket.close()
while True:
client,addr = server.accept()
print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1])
# spin up our client thread to handle incoming data
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()