Python Socket File Transfer Send

29/12/2020
The intention of this article is to learn how to transfer a text file over network through python program. This file transfer is based on server client model to use socket programming in python3+.

Basic Set up Diagram:

Here is the basic set up diagram to run this program.

For simplicity we will call System A as A_client and System B as B_server throughout the article.

File requirements:

We need server.py and this file should be present at server system. In our case server.py should be at B_server system.

Another two files client.py and sample.txt should be present at client system. In our case those two files should be present at A_client system.

Assumptions:

Here are the assumptions:

  • We should have two Linux systems with terminal access.
  • Preferable Linux flavor is Ubuntu.
  • Python3 should be installed.
  • Both Linux systems should able to ping each other. Use ping <Other system IP> command to check ping.
  • One system should act as Server and other system should act as client at one particular time.

Limitations:

Before we proceed further we should know that there are some limitations of this program.

  • Python3+ should be installed to run this program. You may observe error or different behavior if run on python older versions.
  • Only text file can be transferred through this program as of now. Any other format file which does not contain text may fail.
  • Basic programming exceptions have been handled in the program.
  • Program may or may not run on other OS than Ubuntu.
  • Text file should be short at client side as buffer size of 1024 bytes has been used.

Set up requirements:

  • We need at least one Linux system to try out this program. But recommendation is to use two different Linux systems which are connected through network.
  • Two systems should be connected through Ethernet or Wi-Fi or any other connections.

Server Source Code:

https://github.com/linuxhintcode/websamples/blob/master/python_send_file/server.py

Client Source Code:

https://github.com/linuxhintcode/websamples/blob/master/python_send_file/client.py

How to run programs and expected output:

Here are the steps to execute the program.

Step1: Go to B_server system and open a terminal. Short cut to open a terminal is Alt+Ctrl+t.

Step2: Now go the path where server.py is present.

Step3: Now run server.py like below

python3 server.py

There should not be any errors and you should see below prints

Server is listing on port : 9898

Copied file name will be recv.txt at server side

Step4: Now open terminal at A_client system.

Step5: Go to the path where client.py and sample.txt are present.

Step6: Now run client.py like below

python3 client.py <B_server system IP>

We have observed that we need to know the IP address of server. We can execute below command to know the IP address of B_server system.

ifconfig

Now output of A_client system should be like this

################## Below message is received from server ##################
|———————————|
Hi Client[IP address: 192.168.1.102],
**Welcome to Server**
-Server
|———————————|

Step7: Now go to B_server and look for below output

File has been copied successfully
Server closed the connection

Step8: There should be one file name recv.txt at server folder. The content of this recv.txt should be same sample.txt.

So we have successfully copied a file from client to server over network through python program.

Code explanations:

There are two python files server.py and client.py.

Note that we will explain once if any code is same inside server.py and client.py.

  1. server.py:
#!/usr/bin/env python3

This is shebang line which means by default this server.py should use python3. Let’s see one advantage of this line.

We have executed the server.py or client.py like python3 <.py file name>. Now without using python3 we can execute the python file. Follow below commands

Go to super user mode:

su

Give all permission to .py file:

 chmod 777 server.py

Run server.py:

./server.py
import socket
Importing socket library into python program as we are going
to use socket for connection.

s = socket.socket()

We are creating a object “s” to access all methods of socket. This is a OOPs concept.

PORT = 9898

Now we choose one port where server will be listening. We can use non reserved port instead of this.

s.bind((, PORT))

We use bind method to bind server ip address to that port [9898]. One observation is we could have used exact IP address of server in place of first argument of bind method but we choose to left blank as this work fine.

s.bind((IP address, PORT))
file = open("recv.txt", "wb")

We have opened one file name “recv.txt” in server for write mode and got file pointer. This is required as we have to copy one text file from client.

while True:

Let’s start one infinite while loop as server’s job is to wait until a client communicates with server on that 9898 port. So this while loop is required.

conn, addr = s.accept()

This code is to accept any incoming connection request from client. Conn will use “conn” to communicate with client and “addr” is the IP address of client who has sent commotion request to this server on port 9898.

msg = "nn|———————————|n Hi Client[IP address:
 "
+ addr[0] + "], n **Welcome to Server** n -Servern
|———————————|n nn"

This code is to create a message to send to client. This message should be printed on client terminal. This confirms that client is able to communicate with server.

conn.send(msg.encode())

Now we have the message ready, and then send it to client using that “conn”. This code actually send message to client.

RecvData = conn.recv(1024)

This code is receiving any data that is sent from client side. In our case we are expecting the content of sample.txt in “RecvData”.

while RecvData:

One more while loop with condition RecvData is not empty. In our case it’s not empty.

file.write(RecvData)

Once we have content inside “RecvData” then we are writing to that file “recv.txt” using file pointer “file”.

RecvData = conn.recv(1024)

Again trying to receive if there is any data from client. Once “RecvData” has no data the code will break the while loop.

file.close()

This will just close the file pointer as we are done with file write.

conn.close()

This will close the connection with client.

break

This is to come out from infinite while loop at B_server.

  1. client.py:
import sys

Importing sys library as we want use argument facility in python.

if (len(sys.argv) > 1):
  ServerIp = sys.argv[1]
else:
  print("nn Run like n python3 client.py < serverip address > nn")
  exit(1)

As we pass IP address of B_server after file name client.py while running, we need to catch that server IP address inside client.

…..if (len(sys.argv) > 1): => To make sure user passes at least one argument as IP address and catch that IP address insdie “ServerIP”.

If user does not pass at least one argument code shows help and come out from code.

PORT = 9898

This has to be same port as mentioned at B_server side.

s.connect((ServerIp, PORT))

This code will do TCP connection to server IP with that port. Anything wrong at this ponint results into failures in connection.

file = open("sample.txt", "rb")

We are opening “sample.txt” in read mode to read only content.

SendData = file.read(1024)

Reading the content of file and putting inside “SendData” variable.

while SendData:

We are starting one while loop if “SendData” has data. In our case if “sample.txt” is not empty it should have data.

s.send(SendData)

Now we can send content of “sample.txt” to server using socket object “s”.

SendData = file.read(1024)

Again reading if there is anything left. So there will be nothing to read from file “SendData” will be empty and it will come out from while loop.

s.close()

This is not close the connection from client side.

Ubuntu Screenshots Server side

Ubuntu Screenshots Client side

Tested combinations:

  • Linux as server and Linux as client: PASS
  • Linux as client and Linux as server: PASS
  • Linux as server and Windows10 as client: PASS
  • Linux as client and Windows10 as server: PASS

The recommendation is to use two Linux systems for server and client.

Expected Errors:

  1. You can see below error if server is not running on 9898 port

Traceback (most recent call last):

File "client.py", line 22, in <module>
s.connect((ServerIp, PORT))
ConnectionRefusedError: [Errno 111] Connection refused
  1. Below error is seen if IP address is not passed at client side

Run like

python3 client.py < serverip address >
  1. Below error is seen if 1st argument at client side is not an IP address

Traceback (most recent call last):

File "client.py", line 22, in <module>
s.connect((ServerIp, PORT))
socket.gaierror: [Errno –2] Name or service not known
  1. Below error is seen if port is use like 98980

Traceback (most recent call last):

File "client.py", line 22, in <module>
s.connect((ServerIp, PORT))
OverflowError: getsockaddrarg: port must be 065535.
  1. Below error is seen if “sample.txt” is not present at client side.

Traceback (most recent call last):

File "client.py", line 25, in <module>
file = open("sample.txt", "rb")
FileNotFoundError: [Errno 2] No such file or directory: ‘sample.txt’

Conclusion:

Using this program we can send a simple text file from one system to another system through network using python program. This gives us basic learning of python and socket programming also for sending data over network.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Python Plotly Tutorial

Plotly is an analytics company known for developing real-time analytics, statistics and graphing tools for web-based application...
29/12/2020

Python Matplotlib Tutorial

In this lesson on Python Matplotlib library, we will look at various aspects of this data visualisation library which we...
29/12/2020

Python: Vectors, Matrices and Arrays with NumPy

In this lesson, we will look at some neat tips and tricks to play with vectors, matrices and arrays using NumPy library...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Tìm Hiểu Về Thuê Proxy US – Lợi Ích và Cách Sử Dụng Hiệu Quả
11/12/2024

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024

Thuê mua IPv4 giá rẻ, tốc độ nhanh, uy tín #1
28/05/2024