I am working on TCP server to client program.
This is server program.
# TCP Server
print("This is TCP/IP Server")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 1255
s.bind((host, port))
s.listen(5)
socketclient, address = s.accept()
print("Got connected form", address)
data = input(" -> ") # take input
token = True
while token:
socketclient.send(data.encode()) # Send data to the client
data = socketclient.recv(1024).decode()
print("From Client: " + str(data))
data = input(' -> ')
socketclient.close() # Close the connection
This is client program.
# TCP Client
print("This is TCP/IP Client")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 1255
s.connect((host, port))
token = True
while token:
data = s.recv(1024).decode() # Receive from Server
print('Received from Server: ' + data) # Show in terminal
if data == "bye":
print('Connection is Closed')
token = False
s.close()
message = input(" -> ") # Take input again
s.send(message.encode()) # Send message to Server
s.close()
The first message is send by the server and then client reply and so on. But when the server send bye
to client, the client does not close the connection, instead get ready to take input to reply to server. How do I close the client connection when server send bye
to client.