0

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$ 

1 Answer 1

5

Calling conn.close() is indeed the correct way to close the connection.

because I tried use conn.close(), then the server seems stop running now:

Right, because that's what you programmed the server to do. In particular, the client closing the connection causes conn.recv(1024) to return None, which causes your if-test to succeed and then break breaks the server out of its while-loop, and from there the server exits, because there are no further loops for it to execute.

        while True:
            data = conn.recv(1024)
            if not data:
                break

If you want the server to keep running (and accept another socket connection) afterwards, you need to put another while True: loop around the code that starts at the s.accept() line, i.e.:

while True:
   conn, addr = s.accept()
   with conn:
       print('Connected by', addr)
       [...]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.