<small id='1pm62'></small><noframes id='1pm62'>

        <tfoot id='1pm62'></tfoot>

        <i id='1pm62'><tr id='1pm62'><dt id='1pm62'><q id='1pm62'><span id='1pm62'><b id='1pm62'><form id='1pm62'><ins id='1pm62'></ins><ul id='1pm62'></ul><sub id='1pm62'></sub></form><legend id='1pm62'></legend><bdo id='1pm62'><pre id='1pm62'><center id='1pm62'></center></pre></bdo></b><th id='1pm62'></th></span></q></dt></tr></i><div id='1pm62'><tfoot id='1pm62'></tfoot><dl id='1pm62'><fieldset id='1pm62'></fieldset></dl></div>
        • <bdo id='1pm62'></bdo><ul id='1pm62'></ul>
        <legend id='1pm62'><style id='1pm62'><dir id='1pm62'><q id='1pm62'></q></dir></style></legend>
      1. 用 Python(套接字)创建一个简单的聊天应用程序

        Creating a simple Chat application in Python (Sockets)(用 Python(套接字)创建一个简单的聊天应用程序)

          • <legend id='LpULv'><style id='LpULv'><dir id='LpULv'><q id='LpULv'></q></dir></style></legend>
            <i id='LpULv'><tr id='LpULv'><dt id='LpULv'><q id='LpULv'><span id='LpULv'><b id='LpULv'><form id='LpULv'><ins id='LpULv'></ins><ul id='LpULv'></ul><sub id='LpULv'></sub></form><legend id='LpULv'></legend><bdo id='LpULv'><pre id='LpULv'><center id='LpULv'></center></pre></bdo></b><th id='LpULv'></th></span></q></dt></tr></i><div id='LpULv'><tfoot id='LpULv'></tfoot><dl id='LpULv'><fieldset id='LpULv'></fieldset></dl></div>

            <small id='LpULv'></small><noframes id='LpULv'>

                <tfoot id='LpULv'></tfoot>

                  <tbody id='LpULv'></tbody>

                • <bdo id='LpULv'></bdo><ul id='LpULv'></ul>
                  本文介绍了用 Python(套接字)创建一个简单的聊天应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  I'm trying to create a simple chat application using sockets (python). Where a client can send a message to server and server simply broadcast the message to all other clients except the one who has sent it.

                  Client has two threads, which are running forever

                  send: Send simply sends the cleints message to server.

                  receive: Receive the message from the server.

                  Server also has two threads, which are running forever

                  accept_cleint: To accept the incoming connection from the client.

                  broadcast_usr: Accepts the message from the client and just broadcast it to all other clients.

                  But I'm getting erroneous output (Please refer the below image). All threads suppose to be active all the times but Some times client can send message sometimes it can not. Say for example Tracey sends 'hi' 4 times but its not broadcasted, When John says 'bye' 2 times then 1 time its message gets braodcasted. It seems like there is some thread synchronization problem at sever, I'm not sure. Please tell me what's wrong.

                  Below is the code.

                  chat_client.py

                  import socket, threading
                  
                  def send():
                      while True:
                          msg = raw_input('
                  Me > ')
                          cli_sock.send(msg)
                  
                  def receive():
                      while True:
                          sen_name = cli_sock.recv(1024)
                          data = cli_sock.recv(1024)
                  
                          print('
                  ' + str(sen_name) + ' > ' + str(data))
                  
                  if __name__ == "__main__":   
                      # socket
                      cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                  
                      # connect
                      HOST = 'localhost'
                      PORT = 5023
                      cli_sock.connect((HOST, PORT))     
                      print('Connected to remote host...')
                      uname = raw_input('Enter your name to enter the chat > ')
                      cli_sock.send(uname)
                  
                      thread_send = threading.Thread(target = send)
                      thread_send.start()
                  
                      thread_receive = threading.Thread(target = receive)
                      thread_receive.start()
                  

                  chat_server.py

                  import socket, threading
                  
                  def accept_client():
                      while True:
                          #accept    
                          cli_sock, cli_add = ser_sock.accept()
                          uname = cli_sock.recv(1024)
                          CONNECTION_LIST.append((uname, cli_sock))
                          print('%s is now connected' %uname)
                  
                  def broadcast_usr():
                      while True:
                          for i in range(len(CONNECTION_LIST)):
                              try:
                                  data = CONNECTION_LIST[i][1].recv(1024)
                                  if data:
                                      b_usr(CONNECTION_LIST[i][1], CONNECTION_LIST[i][0], data)
                              except Exception as x:
                                  print(x.message)
                                  break
                  
                  def b_usr(cs_sock, sen_name, msg):
                      for i in range(len(CONNECTION_LIST)):
                          if (CONNECTION_LIST[i][1] != cs_sock):
                              CONNECTION_LIST[i][1].send(sen_name)
                              CONNECTION_LIST[i][1].send(msg)
                  
                  if __name__ == "__main__":    
                      CONNECTION_LIST = []
                  
                      # socket
                      ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                  
                      # bind
                      HOST = 'localhost'
                      PORT = 5023
                      ser_sock.bind((HOST, PORT))
                  
                      # listen    
                      ser_sock.listen(1)
                      print('Chat server started on port : ' + str(PORT))
                  
                      thread_ac = threading.Thread(target = accept_client)
                      thread_ac.start()
                  
                      thread_bs = threading.Thread(target = broadcast_usr)
                      thread_bs.start()
                  

                  解决方案

                  Ok I lied in my comment earlier, sorry. The issue is actually in the broadcast_usr() function on the server. It is blocking in the recv() method and preventing all but the currently selected user from talking at a single time as it progresses through the for loop. To fix this, I changed the server.py program to spawn a new broadcast_usr thread for each client connection that it accepts. I hope this helps.

                  import socket, threading
                  
                  def accept_client():
                      while True:
                          #accept    
                          cli_sock, cli_add = ser_sock.accept()
                          uname = cli_sock.recv(1024)
                          CONNECTION_LIST.append((uname, cli_sock))
                          print('%s is now connected' %uname)
                          thread_client = threading.Thread(target = broadcast_usr, args=[uname, cli_sock])
                          thread_client.start()
                  
                  def broadcast_usr(uname, cli_sock):
                      while True:
                          try:
                              data = cli_sock.recv(1024)
                              if data:
                                  print "{0} spoke".format(uname)
                                  b_usr(cli_sock, uname, data)
                          except Exception as x:
                              print(x.message)
                              break
                  
                  def b_usr(cs_sock, sen_name, msg):
                      for client in CONNECTION_LIST:
                          if client[1] != cs_sock:
                              client[1].send(sen_name)
                              client[1].send(msg)
                  
                  if __name__ == "__main__":    
                      CONNECTION_LIST = []
                  
                      # socket
                      ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                  
                      # bind
                      HOST = 'localhost'
                      PORT = 5023
                      ser_sock.bind((HOST, PORT))
                  
                      # listen    
                      ser_sock.listen(1)
                      print('Chat server started on port : ' + str(PORT))
                  
                      thread_ac = threading.Thread(target = accept_client)
                      thread_ac.start()
                  
                      #thread_bs = threading.Thread(target = broadcast_usr)
                      #thread_bs.start()
                  

                  这篇关于用 Python(套接字)创建一个简单的聊天应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Adding config modes to Plotly.Py offline - modebar(将配置模式添加到 Plotly.Py 离线 - 模式栏)
                  Plotly: How to style a plotly figure so that it doesn#39;t display gaps for missing dates?(Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙?)
                  python save plotly plot to local file and insert into html(python将绘图保存到本地文件并插入到html中)
                  Plotly: What color cycle does plotly express follow?(情节:情节表达遵循什么颜色循环?)
                  How to save plotly express plot into a html or static image file?(如何将情节表达图保存到 html 或静态图像文件中?)
                  Plotly: How to make a line plot from a pandas dataframe with a long or wide format?(Plotly:如何使用长格式或宽格式的 pandas 数据框制作线图?)

                  <small id='eLY1D'></small><noframes id='eLY1D'>

                  <i id='eLY1D'><tr id='eLY1D'><dt id='eLY1D'><q id='eLY1D'><span id='eLY1D'><b id='eLY1D'><form id='eLY1D'><ins id='eLY1D'></ins><ul id='eLY1D'></ul><sub id='eLY1D'></sub></form><legend id='eLY1D'></legend><bdo id='eLY1D'><pre id='eLY1D'><center id='eLY1D'></center></pre></bdo></b><th id='eLY1D'></th></span></q></dt></tr></i><div id='eLY1D'><tfoot id='eLY1D'></tfoot><dl id='eLY1D'><fieldset id='eLY1D'></fieldset></dl></div>

                        <bdo id='eLY1D'></bdo><ul id='eLY1D'></ul>
                        <tfoot id='eLY1D'></tfoot>
                          • <legend id='eLY1D'><style id='eLY1D'><dir id='eLY1D'><q id='eLY1D'></q></dir></style></legend>
                              <tbody id='eLY1D'></tbody>