tcp socket python code example

Example 1: send data through tcp sockets python

import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data

Example 2: 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)

Example 3: 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 4: 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()

Example 5: client server python socket

s = socket.socket (socket_family, socket_type, protocol=0)