Amine Amhoume Amine Amhoume - 18 days ago 8
Python Question

Python socket client doesn't exit

I'm trying to develop my simple server/client scripts to send some useful information about systems using platform module and saved in .txt file on the server side ( in order o improve my programming skills ) but when I run the client side it doesn't send any information till I closed using Ctrl+c but what I really want is the client to send informations then it close itself I tried the sys.exit but it doesn't work

this is the server Side

#!/usr/bin/python
import socket
import sys
host = ' '
port = 1060
s = socket.socket()
s.bind(('',port)) #bind server
s.listen(2)
conn, addr = s.accept()
print addr , "Now Connected"
response = conn.recv(1024)
print response
saved = open('saved_data.txt','w+')
saved.write(response) # store the received information in txt file

conn.close()


and this is the client side

#!/usr/bin/python
import socket
import platform
import sys


def socket_co():
port = 1060
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.1.107', port)) # my computer address and the port
system = platform.system()
node = platform.node()
version = platform.version()
machine = platform.machine()
f = s.makefile("r+") #making file to store information ( as I think it do ) using the makefile()
f.write('system: ' + str(system) + '\n')
f.write('node: ' + str(node) + '\n')
f.write('version: ' + str(version) + '\n')
f.write('machine: ' + str(machine) + '\n')
sete = f.readlines() #read lines from the file
s.send(str(sete))
while True:
print "Sending..."
s.close()
sys.exit() #end the operation


def main():
socket_co()

if __name__ == '__main__':
main()

Answer

Data is cached in memory before sending. You have to flush after writing:

   f = s.makefile("r+") #making file to store information ( as I think it do ) using the makefile()
   f.write('system: %s\n' % system)
   f.write('node: %s\n' % node)
   f.write('version: %s\n' % version)
   f.write('machine: %s\n' % machine)
   f.flush()