Example 1: socket programming in python
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
Example 2: python socket server
import socket
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(('', 15555))
while True:
socket.listen(5)
client, address = socket.accept()
print "{} connected".format( address )
response = client.recv(255)
if response != "":
print response
print "Close"
client.close()
stock.close()
Example 3: tcp client using sockets in python
from socket import *
import sys
import json
serverName = ""
serverPort = 6100
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
sample_data = {
"Aparna" : 1,
"Pooja" : 2,
"Shreya" : 3,
"Tanishq" : 4
}
serialized_data = json.dumps(sample_data)
clientSocket.send(str.encode(serialized_data))
response_data = clientSocket.recv(1024)
print("Response data from server : ", response_data.decode())
clientSocket.close()
Example 4: client server python socket
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
Example 5: python socket
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
Example 6: tcp server using sockets in python
import socket
from socket import *
import json
serverPort = 6100
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("", serverPort))
serverSocket.listen(1)
print("The server is listening on PORT 6100")
while 1:
connectionSocket, addr = serverSocket.accept()
data = connectionSocket.recv(1024)
data_loaded = json.loads(data)
print("client Sent :\n ", data_loaded)
connectionSocket.send(str.encode("Mil gya data"))
connectionSocket.close()