Python Forum
How to send/receive data over TCP - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Networking (https://python-forum.io/forum-12.html)
+--- Thread: How to send/receive data over TCP (/thread-15008.html)



How to send/receive data over TCP - Rehan11 - Dec-29-2018

I have tow system one is system A and anothr is system B

System A - Server (pi)
System B - Client (printer)

I want to send a request to the printer
if request accepted, get the data from the printer

I found the two program but I don't understand which one used for my purpose

Client
Here's simple code to send and receive data by TCP in Python
#!/usr/bin/env python

import socket


TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

print "received data:", data
Server
Here's simple code to serve TCP in Python:
#!/usr/bin/env python

import socket


TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 20  # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
print 'Connection address:', addr
while 1:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    print "received data:", data
    conn.send(data)  # echo
conn.close()



RE: How to send/receive data over TCP - cetpaseo336 - Feb-01-2019

hello

write a socket programming with python to send and recive a file over tcp
Here is a part to send a part of data based on the size of the buffer.

msg[i] = file[i].read()
file[i].close()
while 1:
tdata[i], msg[i] = msg[i][:buf], msg[i][buf:]
c.send(tdata[i])

if len(msg[i]) < buf:
break