python tcp server code example
Example 1: python network programming
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 2: 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 3: python tcp socket example
import socket
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Choose mode. s - server, c - client")
mode = input("> ")
if mode == "s":
ip = input("Your computer's ip address: ")
port = 80
socket.bind((ip, port))
socket.listen(1)
sock, addr = socket.accept()
print("Client connected from", addr)
while True:
data = sock.recv(16384)
text = data.decode('utf-8')
print("Message from client:", text)
elif mode == "c":
ip = input("Server ip address: ")
socket.connect((ip, 80))
while True:
socket.send(input("Message: ").encode('utf-8'))
Example 4: client server python socket
s = socket.socket (socket_family, socket_type, protocol=0)