I have socket server and socket client two side programs:
The server:
#!/usr/bin/env python3 #-*- coding:utf-8 -*- # Author:sele import socket HOST = '127.0.0.1' PORT = 65432 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected by', addr) if addr and addr[0] != '127.0.0.44': conn.sendall(b'ip error') # there I want to cut off the socket connection. else: while True: data = conn.recv(1024) if not data: break conn.sendall(data) the client:
#!/usr/bin/env python3 #-*- coding:utf-8 -*- # Author:lele import socket HOST = '127.0.0.1' PORT = 65432 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(b'Hello, world') data = s.recv(1024) print('Received', repr(data)) you see, in my server code: if addr and addr[0] != '127.0.0.44': there I want to close the connection, how to do with it?
whether just add the conn.close() code in that place?
because I tried use conn.close(), then the server seems stop running now:
sele-MacBook-Pro:test01 ldl$ ./tests02-server.py Connected by ('127.0.0.1', 53321) sele-MacBook-Pro:test01 ldl$