Send() Function Of Python Socket Class

Signature:

socket.send(bytes[, flags]

Parameters:

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.

 

Overview:

  • 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

clientSocket.connect(("127.0.0.1",9090));

 

# Send data to server

data = "Hello Server!";

clientSocket.send(data.encode());

 

# Receive data from server

dataFromServer = clientSocket.recv(1024);

 

# Print to the console

print(dataFromServer.decode());

 

 

Output:

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

serverSocket.bind(("127.0.0.1",9090));

serverSocket.listen();

 

# Accept connections

while(True):

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

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

   

    dataFromClient = clientConnected.recv(1024)

    print(dataFromClient.decode());

 

    # Send some data back to the client

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

 

Output:

Accepted a connection request from 127.0.0.1:54916

Hello Server!


Copyright 2019 © pythontic.com