Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python core/tcp.server.py.ipynb
3074 views
Kernel: Python 3

Networking in Python

  • Networking in any programming language is needed to send messages over different across networks.

  • Sockets and Socket APIs are used to send messages across network and they function as IPC(inter-process-Communication).

  • Sockets are created using a set of programming request called socket API (Application Programming Interface).

  • Sockets are the communcation gateway between server & client.

image.png

Steps :

  1. Define Socket(TCP,UDP etc) (g = socket.socket (socket_family, type_of_socket, protocol=value))

  2. Write methods to manage connections form server to client & vice versa.

Common Server Socket Methods

  • listen(): is used to establish and start TCP listener.

  • bind(): is used to bind address (host-name, port number) to the socket.

  • accept(): is used to TCP client connection until the connection arrives.

  • connect(): is used to initiate TCP server connection.

  • send(): is used to send TCP messages.

  • recv(): is used to receive TCP messages.

  • recvfrom():is used to send UDP messages

  • sendto(): is used to send UDP messages

  • close(): is used to close a socket.

Code to Setup Socket virtually(UDP Socket)

from socket import * # use socket.socket() - function udp_1=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ## for UDP ## tcp_2=tcp1=socket.socket(socket.AF_INET, socket.SOCK_STREAM)### for TCP
## Program for Network Connection. import socket import sys # Create a TCP/IP socket stream_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Define host host = 'localhost' # define the communication port port = 8080 # Connect the socket to the port where the server is listening server_address = ((host, port)) print ("connecting") stream_socket.connect(server_address) # Send data message = 'message' stream_socket.sendall(message) # response data = stream_socket.recv(10) print (data) print ('socket closed') ### Save the file with filename - tcpserver.py ,This will open a web server at port 60.

conda -c install socket

pip install socket

import socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "localhost" port = 8000 print (host) print (port) serversocket.bind((host, port)) serversocket.listen(20) print ('server started and listening') while 1: (clientsocket, address) = serversocket.accept() print ("connection found!") data = clientsocket.recv(1024).decode() print (data) r='REceieve' clientsocket.send(r.encode())