How to send continous data from server to client in Python? - python

I am building a server to send data to the client in Python. I would like to continuously send the time until the client closes the connection. So far, I have done :
For the server:
import socket
from datetime import datetime
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at server side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket with server
# and port number
s.bind(('', port))
# allow maximum 1 connection to
# the socket
s.listen(1)
# wait till a client accept
# connection
c, addr = s.accept()
# display client address
print("CONNECTION FROM:", str(addr))
dateTimeObj = str(datetime.now())
print(dateTimeObj)
c.send(dateTimeObj.encode())
# disconnect the server
c.close()
For the client:
import socket
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at client side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# connect it to server and port
# number on local computer.
s.connect(('127.0.0.1', port))
# receive message string from
# server, at a time 1024 B
msg = s.recv(1024)
# repeat as long as message
# string are not empty
while msg:
print('Received date :' + msg.decode())
msg = s.recv(1024)
# disconnect the client
s.close()
How can I modify the server to continously send the current date? At the moment, the server is just sending one date and closing the connection.

you need to use While True loop.
import socket
from datetime import datetime
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at server side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket with server
# and port number
s.bind(('', port))
# allow maximum 1 connection to
# the socket
s.listen(1)
# wait till a client accept
# connection
while True:
c, addr = s.accept()
# display client address
print("CONNECTION FROM:", str(addr))
dateTimeObj = str(datetime.now())
print(dateTimeObj)
c.send(dateTimeObj.encode())
# disconnect the server
c.close()
client:
import socket
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at client side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# connect it to server and port
# number on local computer.
s.connect(('127.0.0.1', port))
# receive message string from
# server, at a time 1024 B
while True:
msg = s.recv(1024)
# repeat as long as message
# string are not empty
while msg:
print('Received date :' + msg.decode())
msg = s.recv(1024)
# disconnect the client
s.close()

Related

Test TCP connection for Client & Server on local machine

I'm trying a simple send/receiver example on my local machine using TCP. The goal is to open a TCP server and send some data. My setup is Python3.6 on Pycharm IDE. I have enabled parallel run of the sender and receiver scripts.
Here is the Server script:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 5005)
print(sys.stderr, 'starting up on %s port %s' % server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print(sys.stderr, 'waiting for a connection')
connection, client_address = sock.accept()
try:
print(sys.stderr, 'connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print(sys.stderr, 'received "%s"' % data)
if data:
print(sys.stderr, 'sending data back to the client')
connection.sendall(data)
else:
print(sys.stderr, 'no more data from', client_address)
break
finally:
# Clean up the connection
connection.close()
And here is the client script:
import socket
TCP_IP = 'localhost'
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.encode('utf-8'))
I verified that both scripts are running and I've used the debugger to parse each line on the sender side. I get no errors but I also don't see that the server receives anything.
EDIT:
I have used an example code from this page
Server:
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data + b' from server')
Client:
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
And I get the expected result:
Received b'Hello, world from server'
Hmm, the client scripts ends immediately after sending its data... This is at least dangerous! Race conditions could cause the connection to be destroyed before anything has been correctly received by the peer. The robust way would be to use a graceful shutdown client side:
...
s.send(MESSAGE.encode('utf-8'))
s.shutdown(socket.SHUT_WR) # tell peer we have nothing more to send
while True:
data = s.recv(256)
if len(data) == 0: # but keep on until peer closes or shutdowns its side
break
After that, I could test that your server script could correctly receive and send back the message:
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> starting up on localhost port 5005
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> waiting for a connection
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> connection from ('127.0.0.1', 62511)
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> received "b'Hello, World!'"
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> sending data back to the client
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> received "b''"
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> no more data from ('127.0.0.1', 62511)
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> waiting for a connection

TCP connection with Python sockets - send() function issue

I am trying to establish TCP connection on the client-side using socket. The first part seem to work fine:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 1234 # The port used by the server
s.connect((HOST, PORT))
Now for the send() the server-side requires:
Once a client is connected it needs to send the following string in order to send a marker: <TRIGGER>XXXX</TRIGGER>In our case XXX is defined as var.trigger
When I write it like s.send(bytes (var.trigger)) it runs with no errors, however, I guess because it is not defined as a string the server does not recognize it.
Thank you in advance
p.s. I don't code in Python so it can be something very basic that I am missing here.
I am also fairly new to python sockets, but I tried this and it worked. My guess is that you need to wait for the data to be sent (on your server side) with something like this:
while True: # Infinite loop
data = conn.recv(1024) # 1024 = number of bytes to be recieves
if not data: # If data is false, or an empty string/list, etc.
break
print("Recieved:", data.decode('utf-8')) # Printing recieved data
The full code is as follows:
import socket
# ========== SERVER ==========
def server():
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) # Setting up socket
HOST = '127.0.0.1' # Localhost
PORT = 65432
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept() # Accepting connection
print("========== SERVER ==========")
print("Connected by:", addr)
while True: # Infinite loop
data = conn.recv(1024) # 1024 = number of bytes to be recieves
if not data: # If data is false, or an empty string/list, etc.
break
print("Recieved:", data.decode('utf-8')) # Printing recieved data
# ========== CLIENT ==========
def client():
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
HOST = '127.0.0.1' # Localhost
PORT = 65432
s.connect((HOST, PORT)) # Connecting to server
print("========== CLIENT ==========")
var = 'XXXX' # Replace with actual variable
s.sendall(f"<TRIGGER>{var}<TRIGGER>".encode('utf-8')) # Sending trigger message
print(f"Sent: <TRIGGER>{var}<TRIGGER>")

Simple python TCP server with sending command to communicate with esp32

I'm new to python programming. I want to create a simple TCP server working with an esp32. The idea of this is to send command data = '{\"accel\",\"gyro\",\"time\":1}' to esp32 via socket and then wait around 10ms for reply from esp32. I tried many examples but nothing works. ESP32 gets my message from this program but I can't receive message from esp32.
import socket
# bind all IP address
HOST = '192.168.137.93'
# Listen on Port
PORT = 56606
#Size of receive buffer
localhost=('0.0.0.0', 56606)
BUFFER_SIZE = 1024
# Create a TCP/IP socket
data = '{\"accel\",\"gyro\",\"time\":1}'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the host and port
s.connect((HOST, PORT))
# send data to server
s.send(bytearray(data, 'utf-8'))
s.serve_forever()
print('Listen for incoming connections')
sock.listen(1)
while True:
client, addr = s.accept()
while True:
content = client.recv(1024)
if len(content) ==0:
break
else:
print(content)
print("Closing connection")
client.close()
I tried more and tried to use other code(see below). Now I get message back but on other port(I can track it by wireshark)
import socket
# Ip of local host
HOST = '192.168.137.93'
# Connect to Port
PORT = 56606
#Size of send buffer
BUFFER_SIZE = 4096
# data to sent to server
message = '{\"accel\",\"gyro\",\"time\":1}'
# Create a TCP/IP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server
s.connect((HOST, PORT))
# send data to server
s.send(bytearray(message, 'utf-8'))
# Receive response from server
data = ""
while len(data) < len(message):
data = s.recv(BUFFER_SIZE)
# Close connection
print ('Server to Client: ' , data)
s.close()
I don't use both of these codes together.
Any hints?

Python socket sends the first message but nothing afterward

My socket sends the first message but nothing afterward.
The output in the server:
What do you want to send?
lol
The client receives:
From localhost got message:
lol
And then it doesn't want to send anything else.
I don't get the what do you want to send printed anymore.
My code:
server.py file:
#!/usr/bin/python3
import socket
# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
print ("got host name:", host)
port = 9996
print("connecting on port:", port)
# bind to the port
serversocket.bind((host, port))
print("binding host and port")
# queue up to 5 requests
serversocket.listen(5)
print("Waiting for connection")
while True:
clientsocket, addr = serversocket.accept()
msg = input("what do you want to send?\n")
clientsocket.send(msg.encode('ascii'))
client.py file:
#!/usr/bin/python3
import socket # create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine
# name
host = socket.gethostname()
port = 9996 # connection to hostname on the port.
s.connect((host, port)) # Receive no more than 1024 bytes
while True:
msg = s.recv(1024)
print(msg.decode("ascii"))
The client only connects once (OK) but the server waits for an incoming connection every start of the while loop.
Since there are no more connection requests by a client, the server will freeze on the second iteration.
If you just want to handle a single client, move clientsocket, addr = serversocket.accept() before the while loop. If you want to handle multiple clients, the standard way is to have the server accept connections inside the while loop and spawn a thread for each client.
You can also use coroutines, but that may be a bit overkill if you are just starting out.

How to send a message from client to server in python

I'm reading two programs in Python 2.7.10 with client and server. How can I modify these programs in order to send a message from client to server?
server.py:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
client.py:
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 80 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
TCP sockets are bi-directional. So, after connection, there is no difference between server and client, you only have two ends of a stream:
import socket # Import socket module
s = socket.socket() # Create a socket object
s.bind(('0.0.0.0', 12345)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print c.recv(1024)
c.close() # Close the connection
and the client:
import socket # Import socket module
s = socket.socket() # Create a socket object
s.connect(('localhost', 12345))
s.sendall('Here I am!')
s.close() # Close the socket when done
The above answer throws an error: TypeError: a bytes-like object is required, not 'str'
However, the following code worked for me:
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 3125
s.bind(('0.0.0.0', port))
print ('Socket binded to port 3125')
s.listen(3)
print ('socket is listening')
while True:
c, addr = s.accept()
print ('Got connection from ', addr)
print (c.recv(1024))
c.close()
client.py:
import socket
s = socket.socket()
port = 3125
s.connect(('localhost', port))
z = 'Your string'
s.sendall(z.encode())
s.close()

Categories

Resources