server client code python 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: tcp server using sockets in python

import socket
from socket import *
import json

serverPort = 6100
serverSocket = socket(AF_INET, SOCK_STREAM)
# Avoiding : Python [Errno 98] Address already in use


serverSocket.bind(("", serverPort))
serverSocket.listen(1)

# TCP Server
print("The server is listening on PORT 6100")

while 1:

	connectionSocket, addr = serverSocket.accept()
	data = connectionSocket.recv(1024)

	# De-serializing data
	data_loaded = json.loads(data)
	
	print("client Sent :\n ", data_loaded)
	
	# Sending response
	connectionSocket.send(str.encode("Mil gya data"))


connectionSocket.close()