Created because it can be used for simple communication confirmation between servers. The book I referred to was python2, so it didn't work subtly. I will upload a slightly modified version for python3.
By the way, the execution assumption is
・ Python 3.7.6
① Create TCPserver.py and TCPclient.py on the same HOST ② Execute TCPserver.py from the terminal ③ Start another terminal and execute TCPclient.py
TCPclient.py
import socket
target_host="127.0.0.1"
target_port=9999
#create socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect to object
client.connect((target_host, target_port))
# data transmission
client.send(b"ABCDEFG")
#recieve data
response = client.recv(4096)
print(response)
TCPserver.py
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("[*] Recieved: %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,))
cliend_handler.start()
左側がTCPserver.py 右側がTCPclient.py Execution result of.
I feel that this amount of code is enough if I just connect it. I also learned how easy it is if the server and client match the ports. Speaking of textbooks, that's right, but when you look at what works with the code This impresses me with this.
Recommended Posts