python client to client message code example
Example 1: send message from server to client python
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))
Example 2: send message from server to client python
import socket
import select
import time
HOST = 'localhost'
PORT = 65439
ACK_TEXT = 'text_received'
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket instantiated')
sock.bind((HOST, PORT))
print('socket binded')
sock.listen()
print('socket now listening')
conn, addr = sock.accept()
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)
def sendTextViaSocket(message, sock):
encodedMessage = bytes(message, 'utf-8')
sock.sendall(encodedMessage)
encodedAckText = sock.recv(1024)
ackText = encodedAckText.decode('utf-8')
if ackText == ACK_TEXT:
print('server acknowledged reception of text')
else:
print('error: server has sent back ' + ackText)
if __name__ == '__main__':
main()