Python套接字客户端没有退出

时间:2016-11-22 21:53:24

标签: python sockets

我正在尝试开发我的简单服务器/客户端脚本,以便使用平台模块发送有关系统的一些有用信息,并保存在服务器端的.txt文件中(以便提高我的编程技能)但是当我运行时客户端它没有发送任何信息,直到我使用Ctrl + c关闭,但我真正想要的是客户端发送信息然后它关闭自己我尝试了sys.exit但它没有工作

这是服务器端

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

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

while True:
       print "Sending..."

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