【问题标题】:How to send a message from the server to a client using sockets如何使用套接字将消息从服​​务器发送到客户端
【发布时间】:2013-09-30 21:32:00
【问题描述】:

服务器

import socket
import sys
HOST = ''
PORT = 9000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
conn, addr = s.accept()
print 'Connecting from: ' + addr[0] + ':' + str(addr[1])
while 1:
    message=raw_input(">")
    s.sendto(message, (addr[0], addr[1]))
    print(s.recv(1024))

如何让它向客户端发送消息? 我可以让它回复客户端发送到服务器的字符串,但在这种情况下,我希望服务器发送第一条消息...... 谁能帮助我,谷歌上的解决方案似乎无法正常工作,我不确定我做错了什么。

【问题讨论】:

  • 套接字必须有某种触发器,除非您只想不断广播。您是否只想在连接事件上发送消息?
  • 当您从对raw_input 的调用中获得message 后,当您调用s.sendto 时,您已经向客户端发送了。

标签: python sockets client-server


【解决方案1】:

由于这是第一个 Google Stack Overflow 结果,我将发布一个完整的、适用于客户端和服务器的示例。您可以从第一个开始。已验证在 Ubuntu 18.04 w/Python 3.6.9 上工作

text_send_server.py:

# text_send_server.py

import socket
import select
import time

HOST = 'localhost'
PORT = 65439

ACK_TEXT = 'text_received'


def main():
    # instantiate a socket object
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('socket instantiated')

    # bind the socket
    sock.bind((HOST, PORT))
    print('socket binded')

    # start the socket listening
    sock.listen()
    print('socket now listening')

    # accept the socket response from the client, and get the connection object
    conn, addr = sock.accept()      # Note: execution waits here until the client calls sock.connect()
    print('socket accepted, got connection object')

    myCounter = 0
    while True:
        message = 'message ' + str(myCounter)
        print('sending: ' + message)
        sendTextViaSocket(message, conn)
        myCounter += 1
        time.sleep(1)
    # end while
# end function

def sendTextViaSocket(message, sock):
    # encode the text message
    encodedMessage = bytes(message, 'utf-8')

    # send the data via the socket to the server
    sock.sendall(encodedMessage)

    # receive acknowledgment from the server
    encodedAckText = sock.recv(1024)
    ackText = encodedAckText.decode('utf-8')

    # log if acknowledgment was successful
    if ackText == ACK_TEXT:
        print('server acknowledged reception of text')
    else:
        print('error: server has sent back ' + ackText)
    # end if
# end function

if __name__ == '__main__':
    main()

text_receive_client.py

# text_receive_client.py

import socket
import select
import time

HOST = 'localhost'
PORT = 65439

ACK_TEXT = 'text_received'


def main():
    # instantiate a socket object
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('socket instantiated')

    # connect the socket
    connectionSuccessful = False
    while not connectionSuccessful:
        try:
            sock.connect((HOST, PORT))    # Note: if execution gets here before the server starts up, this line will cause an error, hence the try-except
            print('socket connected')
            connectionSuccessful = True
        except:
            pass
        # end try
    # end while

    socks = [sock]
    while True:
        readySocks, _, _ = select.select(socks, [], [], 5)
        for sock in readySocks:
            message = receiveTextViaSocket(sock)
            print('received: ' + str(message))
        # end for
    # end while
# end function

def receiveTextViaSocket(sock):
    # get the text via the scoket
    encodedMessage = sock.recv(1024)

    # if we didn't get anything, log an error and bail
    if not encodedMessage:
        print('error: encodedMessage was received as None')
        return None
    # end if

    # decode the received text message
    message = encodedMessage.decode('utf-8')

    # now time to send the acknowledgement
    # encode the acknowledgement text
    encodedAckText = bytes(ACK_TEXT, 'utf-8')
    # send the encoded acknowledgement text
    sock.sendall(encodedAckText)

    return message
# end function

if __name__ == '__main__':
    main()

【讨论】:

    【解决方案2】:

    使用 'accept' 返回的套接字对象从连接的客户端发送和接收数据:

    while 1:
        message=raw_input(">")
        conn.send(message)
        print conn.recv(1024)
    

    【讨论】:

      【解决方案3】:

      您只需使用 send
      Server.py

      import socket
      
      s = socket.socket()
      
      port = 65432
      
      s.bind(('0.0.0.0', port))
      
      s.listen(5)
      
      while True:
          c, addr = s.accept()
      
          msg = b"Hello World!"
      
          c.send(msg)
      

      Client.py

      import socket             
      
      s = socket.socket()         
      
      port = 65432                
      
      s.connect(('127.0.0.1', port)) 
      

      【讨论】:

        猜你喜欢
        • 2013-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-28
        • 2020-06-01
        • 2016-08-31
        相关资源
        最近更新 更多