如何使用套接字从服务器向客户端发送消息

7

服务器

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))

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


除非您只想不断广播,否则必须有某种套接字触发器。您是要在连接事件上仅发送一条消息吗? - Slater Victoroff
1
当您从raw_input调用中获取message后,调用s.sendto向客户端发送数据。 - Eric Urban
3个回答

6

由于这是第一个在Google Stack Overflow上的结果,我将为客户端和服务器端提供一个完整的、可工作的示例。您可以先从任何一个开始。经验证,在Ubuntu 18.04中使用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()

3

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

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

0

你只需要使用 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)) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接