【问题标题】:How to send a message from client to server in python如何在python中从客户端向服务器发送消息
【发布时间】:2016-09-10 15:56:45
【问题描述】:

我正在阅读带有客户端和服务器的 Python 2.7.10 中的两个程序。如何修改这些程序以便将消息从客户端发送到服务器?

server.py:

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

client.py:

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 80              # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

【问题讨论】:

    标签: python networking server client


    【解决方案1】:

    TCP 套接字是双向的。所以,连接后,服务器和客户端没有区别,你只有一个流的两端:

    import socket               # Import socket module
    
    s = socket.socket()         # Create a socket object
    s.bind(('0.0.0.0', 12345))        # Bind to the port
    
    s.listen(5)                 # Now wait for client connection.
    while True:
       c, addr = s.accept()     # Establish connection with client.
       print 'Got connection from', addr
       print c.recv(1024)
       c.close()                # Close the connection
    

    和客户:

    import socket               # Import socket module
    
    s = socket.socket()         # Create a socket object
    s.connect(('localhost', 12345))
    s.sendall('Here I am!')
    s.close()                     # Close the socket when done
    

    【讨论】:

      【解决方案2】:

      以上答案抛出错误:TypeError: a bytes-like object is required, not 'str' 但是,以下代码对我有用:

      server.py

      import socket
      import sys
      
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      port = 3125
      s.bind(('0.0.0.0', port))
      print ('Socket binded to port 3125')
      s.listen(3)
      print ('socket is listening')
      
      while True:
          c, addr = s.accept()
          print ('Got connection from ', addr)
          print (c.recv(1024))
          c.close()
      

      client.py:

      import socket
      
      s = socket.socket()
      port = 3125
      s.connect(('localhost', port))
      z = 'Your string'
      s.sendall(z.encode())    
      s.close()
      

      【讨论】:

        猜你喜欢
        • 2019-07-09
        • 2013-06-24
        • 2017-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-15
        相关资源
        最近更新 更多