Send() Function Of Python Socket Class


socket.send(bytes[, flags])


bytes – The data to be sent in bytes. In case the data is in string format, the encode() method of str can be called to convert it into bytes.

flags – This is an optional parameter. The parameter flags has a default value of 0. The valid values of the flags parameter as supported by the operating system to be used. Multiple flags values are applied bitwise OR and sent.



  • The send()method of Python's socket class is used to send data from one socket to another socket.
  • The send()method can only be used with a connected socket. That is, send() can be used only with a TCP based socket and it can not be used with UDP socket.
  • The send() method can be used to send data from a TCP based client socket to a TCP based client-connected socket at the server side and vice versa.
  • The data sent should be in bytes format. String data can be converted to bytes by using the encode() method of string class.

Example – A TCP based Client:

#----- A simple TCP client program in Python using send() function -----

import socket


# Create a client socket

clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);


# Connect to the server



# Send data to server

data = "Hello Server!";



# Receive data from server

dataFromServer = clientSocket.recv(1024);


# Print to the console





Hello Client!


Example – A TCP based Server:

#----- A simple TCP based server program in Python using send() function -----


import socket


# Create a stream based socket(i.e, a TCP socket)

# operating on IPv4 addressing scheme

serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);


# Bind and listen




# Accept connections


    (clientConnected, clientAddress) = serverSocket.accept();

    print("Accepted a connection request from %s:%s"%(clientAddress[0], clientAddress[1]));


    dataFromClient = clientConnected.recv(1024)



    # Send some data back to the client

    clientConnected.send("Hello Client!".encode());



Accepted a connection request from

Hello Server!

Copyright 2024 ©