如何在整个应用程序打开期间保存套接字连接以通过它发送数据?

时间:2018-08-31 05:57:36

标签: python multithreading sockets networking tcp

我注意到我可以接受套接字连接并将该连接保存在字典中。我希望另一个对象可以访问此连接,以便该对象可以随时对其进行写入。这是我的尝试:

socket.py

class Socket:
    def __init__(self, host, port):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((host, port))
        self.s.listen(5)
        self.connections = {}

    def start(self):
        print('Listening to port 10005')
        while True:
            conn, addr = self.s.accept()
            print('connected to: ' + addr[0] + ':' + str(addr[1]))
            self.connections[str(addr[1])] = conn
        self.s.close()

   def bother(self, addr, msg):
        if addr in self.connections:
           socket = self.connections[addr]
           secket.send(msg.encode('utf-8'))
           data = socket.recv(1024)
           print(data.decode('utf-8'))


 if __name__ == '__main__':
    socket = Socket('0.0.0.0', 10005)
    socket.start()

    while True:
        addr = input('Enter addr: ')
        msg = input('Enter msg: ')
        socket.bother(addr, msg)

这是device_sim.py

  // device_sim.py
  import socket
  from _thread import *

  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect(('localhost', 10005))

  while True:  
      data = s.recv(1024)
      s.send('Dont talk to me'.encode('utf-8'))

我希望服务器能够接受套接字连接并将其保存到字典中。我希望另一个进程能够与该特定套接字通信,因为它知道连接字典中的ID,并通过映射到该ID的套接字写入数据。

我似乎无法输入addr,因为它似乎在start()上受阻。是否可以实现我想要的?谢谢

0 个答案:

没有答案