2016-11-22 7 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()を取得することはありません。送信が完了するまで送信メソッドはブロックされませんか? – 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..." 

loops forever。だから問題は送信部にない。

+0

whileループを削除しても、クライアントはサーバーに情報を送信しませんCtrl + Cで –

関連する問題