tcp socket programming in python code example

Example 1: socket programming in python

#!/usr/bin/env python3

import socket

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

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 network programming

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

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) #data serialized

# clientSocket.send(str.encode(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: python tcp socket example

# Basic example where server accepts messages from client.

# importing socket library
import socket

# socket.AF_INET means we're using IPv4 ( IP version 4 )
# socket.SOCK_STREAM means we're using TCP protocol for data transfer
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
  
  # Binding socket to specified ip address and port
  socket.bind((ip, port))
  
  # This is max ammount of clients we will accept
  socket.listen(1)
  
  # Accepting connection from client
  sock, addr = socket.accept()
  print("Client connected from", addr)
  
  # Receiving data from client
  while True:
    data = sock.recv(16384) # Raw data from client
    text = data.decode('utf-8') # Decoding it
    
    print("Message from client:", text)
    
elif mode == "c":
  ip = input("Server ip address: ")
  
  # Connecting to server
  socket.connect((ip, 80))
  
  # Sending data
  while True:
    socket.send(input("Message: ").encode('utf-8'))

Example 5: python socket

import socket

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

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)