2016-11-22 55 views
0

我想发展我的简单的服务器/客户端脚本,以使用平台模块发送关于系统的一些有用的信息和(保存在服务器端的.txt文件,以便Ø提高我的编程技巧)但是当我运行客户端时,它不会发送任何信息,直到我关闭使用Ctrl + c,但我真正想要的是客户端发送信息,然后关闭自己我试过sys.exit但它不起作用Python的套接字客户端不会退出

这是服务器端

#!/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() 

,这是客户端

#!/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() 
+1

你有一个真正虽然这将循环永远,你将永远不会到接近或sys.exit(),这是没有必要的。 send方法在发送完成之前是否阻塞? – Rob

+0

即使删除了while循环的客户端不发送任何信息到服务器,直到我停止它用Ctrl + C –

回答

1

数据在发送之前被缓存在内存中。你必须flush写入后:

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() 
+0

谢谢,这正是我错过了 –

0
while True: 
     print "Sending..." 

永远循环。所以问题不在发送部分。

+0

即使删除了while循环的客户端不发送任何信息到服务器,直到我停止它与Ctrl + C –