
What is socket programming?
Why use Python for socket programming?
Python Socket Programming: Client-to-Server Communication
import socket
# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind socket to public host, and a port
serversocket.bind((host, port))
# become a server socket
serversocket.listen(5)
while True:
# establish a connection
clientsocket, addr = serversocket.accept()
print (‘Got a connection from %s’ % str(addr))
#send a “thank you” message to the client.
message = Thank you for connecting + ‘\r\n’
clientsocket.send(message.encode('ascii'))
# close the client connection
clientsocket.close()
import socket
# create a socket object
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
clientsocket.connect((host, port))
# receive “welcome message” from server.
message = clientsocket.recv(1024)
clientsocket.close()
print (message.decode ('ascii'))
Python Socket Programming: Client-to-Client Communication
Client-to-Client Communication using PubNub
pip install pubnub Top of Form
from pubnub import PubNub
pubnub = PubNub(publish_key=’YOUR_PUBLISH_KEY’, subscribe_key=’YOUR_SUBSCRIBE_KEY’)
def callback(message, channel):
print(‘Received message:’, message)
def error_callback(error):
print(‘PubNub error:’, error)
pubnub.subscribe().channels(‘my_channel’).execute(callback=callback, error=error_callback)
message = {'text': 'Hello, world!'}
pubnub.publish().channel(‘my_channel’).message(message).pn_async(lambda result, status: print(result, status))
Are You Interested in Building a Top-Class Website or Mobile App?