Python Forum

Full Version: Simple send and recive string Server/Client
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there, i'm new so sorry if I miss a rule, I read it but i'm not sure if get them all
And sorry for my english i'm learning this Big Grin

Mi problem is next: In this moment I have a simple multi thread server and a client that send and recieve a string

The questions: What occur if the client close the program? The listening of client from server is still running? If not close, how can I close the connection if the client show no activity during some time of inactivity?

There is my code:

Server:

import socket
import threading

host = "127.0.0.1"
port = 27501
maxClients = 1000

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket Created")
sock.bind((host, port))
print ("Socket bind complete")
sock.listen(maxClients)
print ("Socket now listening")

def action(*args):
    conn = args[0]
    addr = args[1]
    try:
        print('Connection with: ', format(addr))
        while True:
            data = conn.recv(4096)
            if data:
                print('Recieved: ', format(data.decode('utf-8')))
                answer = "SERVER: You send > "+data.decode('utf-8')
                conn.send(answer.encode("utf-8"))
                break
    finally:
        doSomeThing = 1

while True:
    conn, addr = sock.accept()
    threading.Thread(target=action, args=(conn, addr)).start()
Client:

import socket
import sys

server_address = ('localhost', 27501)

while True:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(server_address)
    msg = input("Send data > ")   
    try:
             
        print ("Send: ",msg)
        sock.sendall(msg.encode("utf-8"))
         
        amount_received = 0
        amount_expected = len(msg)
             
        while amount_received < amount_expected:
            data = sock.recv(4096)
            amount_received += len(data)
            print ("Answer\n-----> ", data.decode("utf-8"))
         
    finally:
        doSomeThing = 1
        
    opc = input("[ENTER] other msg\n[Some value] Close\n")
    if (opc != ""):
        break
That is all, I hope you can help
Bye Folks

Sorry this is real code, the last close the connection before the action

Server:

import socket
import threading
import datetime

host = "127.0.0.1"
port = 27501
maxClients = 1000


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket Created")
sock.bind((host, port))
print ("Socket bind complete")
sock.listen(maxClients)
print ("Socket now listening")

def action(*args):
    conn = args[0]
    addr = args[1]
    try:
        print('Connection with: ', format(addr))
        while True:
            data = conn.recv(4096)
            if data:
                print('Recieved: ', format(data.decode('utf-8')))
                answer = "SERVER: You send > "+data.decode('utf-8')
                conn.send(answer.encode("utf-8"))
    finally:
        return 1

while True:
    conn, addr = sock.accept()
    threading.Thread(target=action, args=(conn, addr)).start()
Client:
import socket
import threading
import datetime

host = "127.0.0.1"
port = 27501
maxClients = 1000


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket Created")
sock.bind((host, port))
print ("Socket bind complete")
sock.listen(maxClients)
print ("Socket now listening")

def action(*args):
    conn = args[0]
    addr = args[1]
    try:
        print('Connection with: ', format(addr))
        while True:
            data = conn.recv(4096)
            if data:
                print('Recieved: ', format(data.decode('utf-8')))
                answer = "SERVER: You send > "+data.decode('utf-8')
                conn.send(answer.encode("utf-8"))
    finally:
        return 1

while True:
    conn, addr = sock.accept()
    threading.Thread(target=action, args=(conn, addr)).start()
One way you could try is to send one last message to the server saying that the client is now logged off. if you are running a console application catch the keyboard interrupt.
The best way to clean up in this scenario would be to have a timer running on the server that closes everything after some amount of time.
from time import time
start = time()
# some communication stuff
end = time()
if end - start >= time_threshold:
      # close server or reset server
make sure this only happens after a client connected to the server :)