How to send a message from the server to a client using sockets
Asked Answered
M

3

7

Server

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

How do I make this send a message to the client? I can make it reply to a string the client sends to the server, but in this case I want the server to send the first message... Can anyone help me, The solutions on google don't seem to work properly and I'm not sure what I'm doing wrong.

Madra answered 30/9, 2013 at 21:32 Comment(2)
There has to be some kind of trigger for the socket, unless you just want to constantly broadcast. Are you looking to just send a message on a connection event?Dangelo
You are already sending to the client when you call s.sendto after getting message from a call to raw_input.Shortwinded
M
6

Since this is the 1st Google Stack Overflow result for this, I'll post a complete, working example for both a client and a server. You can start either 1st. Verified working on 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()
Malacology answered 16/4, 2020 at 1:9 Comment(0)
S
3

Use the returned socket object from 'accept' for sending and receiving data from a connected client:

while 1:
    message=raw_input(">")
    conn.send(message)
    print conn.recv(1024)
Sauerbraten answered 30/9, 2013 at 21:41 Comment(0)
T
0

You just have to use 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)) 
Throve answered 30/5, 2021 at 23:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.