server client code python internet code example
Example 1: 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 2: 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)