Python simple tcp server

Simple TCP client and server using python

There are powerful libraries and tools written in python. In the core part of these libraries and tools is the socket module. This module provides access to the BSD socket interface and avaliable on numerous platforms, Unix, Window, and Mac OS X etc. Here, I’m going to create a TCP client and TCP server to test and transfer data.

TCP client

  1. Connection would be successful.
  2. Server would wait for client to send data first.
  3. Server would response in a short time.
1 2 3 4 5 6 7 8 9 10 11 12
import socket target_host = "0.0.0.0" target_port = 27700 # create a socket connection client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # let the client connect client.connect((target_host, target_port)) # send some data client.send("SYN") # get some data response = client.recv(4096) print response 

TCP server

To establish a TCP server, we would build a multi-threaded TCP server. After binding the listening host ip and port, specify the maximum number value of the connections made to the socket.
Everytime the server accept a connection, store the socket object into client variable and create a new thread to handle this connection using the handle_client function.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
import socket import threading bind_ip = "0.0.0.0" bind_port = 27700 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip, bind_port)) server.listen(5) print "[*] Listening on %s:%d" % (bind_ip, bind_port) # This is the thread we handle the data from the client def handle_client(client_socket): # show the data from the client request = client_socket.recv(1024) print "[*] Received: %s" % request # Return a packet client_socket.send("ACK!") client_socket.close() while True: client, addr = server.accept() print "[*] Accepted connection from: %s:%d" % (addr[0], addr[1]) # activate the function to handle the data from client client_handler = threading.Thread(target = handle_client, args=(client,)) client_handler.start() 

Demonstration

Execute the server and then execute the client in another terminal window. This is the output in the server window.

python tcp_server.py [*] Listening on 0.0.0.0:27700 [*] Accepted connection from: 127.0.0.1:50061 [*] Received: SYN

Conclusion

It's quite easy but powerful to write these TCP connections in Python. Afterward, there would be more extension of these applications.

Источник

How to create a simple Python TCP/IP Server and Client?

IPC is a communication mechanism that an Operating System offers for processes to communicate with each other. There are various types of IPCs such as:

  • Pipes
  • Sockets
  • Files
  • Signals
  • Shared Memory
  • Message Queues/ Message Passing

Sockets

Sockets are used to send data over the network either to a different process on the same computer or to another computer on the network.

There are four types of sockets namely,

  • Stream Sockets
  • Datagram Sockets
  • Raw Sockets
  • Sequenced Packet Sockets

Stream sockets and datagram sockets are the two most popular choices.

Stream Sockets Datagram Sockets
Guaranteed delivery No delivery guarantees
Uses TCP (Transmission Control Protocol) Used UDP (User Datagram Protocol)
Needs an open connection Don’t need to have an open connection

How are sockets used in Distributed Systems?

Distributed Systems are built using the concept of Client Service architectures.

  • Clients send requests to servers
  • Servers send back responses or error codes accordingly

The communication across servers and clients in a distributed system uses sockets as a popular form of IPC. Sockets are nothing but a combination of

Each machine (with an IP address) has several applications running on it. We need to know on which port an application is running in to send requests to it.

What is TCP/IP?

We will go into the details of communication protocols in a different article and stick to the basics for today. TCP stands for Transmission Control Protocol, a communications protocol for computers to exchange information over a network.

IP stands for Internet Protocol. IP identifies the IP address of the applications or devices to send data to and forms the Network Layer in the OSI stack. TCP defines how to transport the data over the network. Ensuring delivery guarantee is still TCP’s job.

When we send an HTTP request to a server, we first establish a TCP connection, so HTTP sits on top of TCP as the transport layer. When a user types a URL into the browser, the browser sets up a TCP socket using the IP address and port number and starts sending data to that socket. This request is sent as bytes in the form of data packets over the network. The server will then respond to the request. The benefits of a TCP connection is that a server sends acknowledgement of each packet based on which the client retransmits data in case some packets get dropped. Each packet has a sequence number that the server uses to assemble them upon receiving.

Now let’s look at an example Python program on how to write a simple script to setup a TCP/IP server and client.

Python TCP/IP server

import socket # Set up a TCP/IP server tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to server address and port 81 server_address = ('localhost', 81) tcp_socket.bind(server_address) # Listen on port 81 tcp_socket.listen(1) while True: print("Waiting for connection") connection, client = tcp_socket.accept() try: print("Connected to client IP: <>".format(client)) # Receive and print data 32 bytes at a time, as long as the client is sending something while True: data = connection.recv(32) print("Received data: <>".format(data)) if not data: break finally: connection.close()

Python TCP/IP Client

import socket # Create a connection to the server application on port 81 tcp_socket = socket.create_connection(('localhost', 81)) try: data = str.encode(‘Hi. I am a TCP client sending data to the server’) tcp_socket.sendall(data) finally: print("Closing socket") tcp_socket.close()

Terminal Output

Waiting for connection Connected to client IP: ('127.0.0.1', 65483) Received data: Hi. I am a TCP c Received data: lient sending da Received data: ta to the server Received data: Waiting for connection

To find and kill any applications running on a port.

List the processes running on port 81

Get the PID number and kill the process

Hope you enjoyed learning how to setup a simple TCP/IP server and client using Python.

Источник

Читайте также:  Ext php gd2 dll
Оцените статью