Python socket programming and LED interfacing - python

I'm trying to write socket programming in python. Whenever client sends message to server, LED should start blinking.
I'm running server program on Raspberry pi and client on PC.
Here is the code of server which is running on my Pi.
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import time
import RPi.GPIO as GPIO # Import GPIO library
GPIO.setmode(GPIO.BOARD) # Use board pin numbering
GPIO.setup(11, GPIO.OUT) # Setup GPIO Pin 11 to OUT
GPIO.output(11,False) # Init Led off
def led_blink():
while 1:
print "got msg" # Debug msg
GPIO.output(11,True) # Turn on Led
time.sleep(1) # Wait for one second
GPIO.output(11,False) # Turn off Led
time.sleep(1) # Wait for one second
GPIO.cleanup()
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # Port
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
msg = c.recv(1024)
msg1 = 10
if msg == msg1:
led_blink()
print msg
c.close()
Here is the code of client which is running on my PC.
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # port
s.connect((host, port))
s.send('10')
s.close
I'm able to receive the message from client, But not able to blink the LED.
Sorry I'm new to coding. I've pretty good knowledge in hardware but not in software.
Please help me.

Try this on your PC or Raspberry and then edit accordingly:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
def led_blink(msg):
print "got msg", msg # Debug msg
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print "Listening"
c, addr = s.accept() # Establish connection with client.
while True:
msg = c.recv(1024)
print 'Got connection from', addr
if msg == "Exit":
break
led_blink(msg)
c.close()
and:
#!/usr/bin/python # This is client.py file
import socket, time # Import socket module
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # port
s.connect((host, port))
x=0
for x in range(10):
s.send('Message_'+str(x))
print x
time.sleep(2)
s.send('Exit')
s.close
Note that I am using both the server and client on the same machine 127.0.0.1 and removed the GPIO bits as I don't have them available.

You are comparing a string "10" with a number 10. Change your server code to :
msg1 = "10"

Related

ngrok tcp address cant connect to my python chat app (python3)

Q: "ngrok tcp address cant connect to my python chat app (python3)"
Description: i got a problem with linking my ngrok tcp address into my python chat app and i always end up getting this error: "OSError: [WinError 10049] The requested address is not valid in its context". And i also get the same problem with my client script(client.py)
here's the code:
# file: server.py
import socket
from threading import Thread
from pyngrok import ngrok
# server's IP address
SERVER_HOST = "ngrok tcp address"
SERVER_PORT = ngrok tcp address port # port we want to use
separator_token = "<SEP>" # we will use this to separate the client name & message
# initialize list/set of all connected client's sockets
client_sockets = set()
# create a TCP socket
s = socket.socket()
# make the port as reusable port
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# bind the socket to the address we specified
s.bind((SERVER_HOST, SERVER_PORT))
# listen for upcoming connections
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
def listen_for_client(cs):
"""
This function keep listening for a message from `cs` socket
Whenever a message is received, broadcast it to all other connected clients
"""
while True:
try:
# keep listening for a message from `cs` socket
msg = cs.recv(1024).decode()
except Exception as e:
# client no longer connected
# remove it from the set
print(f"[!] Error: {e}")
client_sockets.remove(cs)
else:
# if we received a message, replace the <SEP>
# token with ": " for nice printing
msg = msg.replace(separator_token, ": ")
# iterate over all connected sockets
for client_socket in client_sockets:
# and send the message
client_socket.send(msg.encode())
while True:
# we keep listening for new connections all the time
client_socket, client_address = s.accept()
print(f"[+] {client_address} connected.")
# add the new connected client to connected sockets
client_sockets.add(client_socket)
# start a new thread that listens for each client's messages
t = Thread(target=listen_for_client, args=(client_socket,))
# make the thread daemon so it ends whenever the main thread ends
t.daemon = True
# start the thread
t.start()
# close client sockets
for cs in client_sockets:
cs.close()
# close server socket
s.close()
# file: client.py
import socket
import random
from threading import Thread
from datetime import datetime
from colorama import Fore, init, Back
# init colors
init()
# set the available colors
colors = [Fore.BLUE, Fore.CYAN, Fore.GREEN, Fore.LIGHTBLACK_EX,
Fore.LIGHTBLUE_EX, Fore.LIGHTCYAN_EX, Fore.LIGHTGREEN_EX,
Fore.LIGHTMAGENTA_EX, Fore.LIGHTRED_EX, Fore.LIGHTWHITE_EX,
Fore.LIGHTYELLOW_EX, Fore.MAGENTA, Fore.RED, Fore.WHITE, Fore.YELLOW
]
# choose a random color for the client
client_color = random.choice(colors)
# server's IP address
# if the server is not on this machine,
# put the private (network) IP address (e.g 192.168.1.2)
SERVER_HOST = "ngrok tcp address"
SERVER_PORT = ngrok tcp address port # server's port
separator_token = "<SEP>" # we will use this to separate the client name & message
# initialize TCP socket
s = socket.socket()
print(f"[*] Connecting to {SERVER_HOST}:{SERVER_PORT}...")
# connect to the server
s.connect((SERVER_HOST, SERVER_PORT))
print("[+] Connected.")
# prompt the client for a name
name = input("Enter your name: ")
def listen_for_messages():
while True:
message = s.recv(1024).decode()
print("\n" + message)
# make a thread that listens for messages to this client & print them
t = Thread(target=listen_for_messages)
# make the thread daemon so it ends whenever the main thread ends
t.daemon = True
# start the thread
t.start()
while True:
# input message we want to send to the server
to_send = input()
# a way to exit the program
if to_send.lower() == 'q':
break
# add the datetime, name & the color of the sender
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
to_send = f"{client_color}[{date_now}] {name}{separator_token}{to_send}{Fore.RESET}"
# finally, send the message
s.send(to_send.encode())
# close the socket
s.close()

Clients not receiving data from Server python

I am new to Python. I am writing a Server program and a Client program. In here, Server plays the role of distributing the data to the multiple clients. It works great. My task is to distribute the data from the server by using server.py file. Whenever any clients wants it, he just execute clients.py in his laptop and get the results. But in here, the Server starts distributing the data. The ip, the server using was 127.0.1.1. It is not taking the network provided ip. How to make it use the ip provided by LAN. When the clients from other computer execute clients.py file . It shows Connection refused error. Note that we are all connected in the LAN. How to solve it and make clients receive the data.
Here's the sample Client Code:
import socket
import os
from threading import Thread
import socket
import time
s = socket.socket()
host = '127.0.1.1'
port = 10016
print(host)
s.connect((host, port))
while True:
print(s.recv(1024))
s.close()
Sample Server Code:
import socket
import os
from threading import Thread
import thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.gethostname()
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = "Hi Steven!!!" + timestamp
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
configure the ip provided by LAN to client.py (ip in LAN like this: 192.168.122.33)
host = 'ip provided by LAN'
Finally found the answer
In the '/etc/hosts' file content, i have an IP address mapping with '127.0.1.1' to my hostname. This is causing the name resolution to get 127.0.1.1. I commented this line. Now it works. Every one in my lan can receive the data
Server Code:
import socket
import os
from threading import Thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.getfqdn() # it gets ip of lan
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = ("Hi Steven!!!" + timestamp).encode()
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
Client Code:
import socket
import os
import time
s = socket.socket()
host = '192.168.1.43' #my server ip
port = 10016
print(host)
print(port)
s.connect((host, port))
while True:
print((s.recv(1024)).decode())
s.close()

Python sockets and commands

I'm trying to send console commands from one machine to another using Python sockets. I want the server to send back the results of the command to the client. If the client types "ls" I want the server to send back the results of running that command. Instead of the expected result, the server just says "action completed: ls". How can I fix this so the server will run the expect commands and return the result?
Server:
import socket
from subprocess import call
def main():
host = '127.0.0.1'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
print('Connection established: ' + str(addr))
while True:
try:
data = c.recv(1024).decode('utf-8')
print('sending data: ' + data)
c.send(data.encode('utf-8'))
if data == 'q':
break
except NameError:
error = 'Command does not exist'
c.send(error.encode('utf-8'))
continue
except SyntaxError:
error = 'Command does not exist'
c.send(error.encode('utf-8'))
continue
c.close()
Client:
import socket
from subprocess import call
def main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host, port))
message = str(input('> '))
while message != 'q':
try:
s.send(message.encode('utf-8'))
data = s.recv(1024).decode('utf-8')
print('Action completed: %s' % data)
message = str(input('> '))
except NameError:
print("Command not recognized.")
continue
except SyntaxError:
print("Command not recognized")
continue
I recently built a socket connection in order to communicate with an android device.
I decided to use UDP instead of TCP (which is what you did). For UDP as well as TCP you need a sender and a receiver on both sides of the communication.
The port number that is received in the "addr" variable changes with every connection, so you cannot use it.
What I did, I assigned two different ports one for sending from A to B and the other port to send from B to A.
Here is my server code:
import socket # socket connection
import threading # Multithreading
import time # Timeing
# ----------------------------------------------
# Variables
# ----------------------------------------------
UDPListen2Port = 12345
UDPSend2Port = 123456
Listen2IP = '' # input your local IP here
# ----------------------------------------------
# Threading class
# ----------------------------------------------
class signalProcessingThread(threading.Thread):
def __init__(self, iP, cmdIn):
threading.Thread.__init__(self)
self.iP = iP
self.cmdIn = cmdIn
def run(self):
print("Recv--", self.iP ,"--", self.cmdIn) # Display Thread Info
cmdOut = self.EvalMessage() # Actual signal processing
byteOut = bytes(cmdOut.encode("utf-8")) # Convert Server reply to bytes
sock.sendto(byteOut,(self.iP,UDPSend2Port)) # Send Server Reply to Socket
# ----------------------------------------------
# Initialize Socket
# ----------------------------------------------
sock = socket(AF_INET, SOCK_DGRAM) # -- UDP -- connection
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # in case the port was not properly closed before
sock.bind((Listen2IP,UDPListen2Port)) # bind to the port
# ----------------------------------------------
# Listen to Socket
# ----------------------------------------------
while True:
try: # wait for a connection
data,addr = sock.recvfrom(66507) # number of bytes in the message
msg = data.decode('utf-8')
newThread = signalProcessingThread(addr[0],msg)
newThread.start()
except KeyboardInterrupt:
print('Connection failed')
sock.close()
sock.close()
The client code is quite similar, with the difference that it doesn't necessarily need to run in a thread. Hope I could help.

Socket.error: [Errno 10022] An invalid argument was supplied

#!/usr/bin/env python
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('192.168.1.123', 5162))
clientsocket.send('getval.1')
clientsocket.close
clientsocket.bind(('192.168.1.124', 5163))
clientsocket.listen(1)
while True:
connection, address=clientsocket.accept()
value=connection.recv(1024)
print value
I'm trying to get python to send a message to the server, and in return the server responds. Yet when I execute this code it gives me
Socket.error: [Errno 10022] An invalid argument was supplied
It seems you wrote a mixed code of server and client
Here a simple sample of codes for socket programming the first on server side and the second on client
Server side code:
# server.py
import socket
import time
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
and now the client
# client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" % tm.decode('ascii'))
The server simply remained listened for any client and when it finds out a new connection it returns current datetime and closes the client connection

Basic UDP & TCP Program

I am trying to write a simple server that will listen for one set of messages on UDP and another set of messages on TCP. I have written the following code:
from threading import Thread
import time
import socket
#define UDP listening function
def UDPListen():
Listening_UDP_Port = 300
Listening_IP = "127.0.0.1"
BUFFER_SIZE = 64
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # IPv4, UDP
sock.bind((Listening_IP, Listening_UDP_Port))
while True:
data, address = sock.recvfrom(BUFFER_SIZE)
print "UDP Messsage from address: ", address
print "Message: ", data
# END UPDListen() FUCNTION
#define a TCP listening function
def TCPListen():
Listening_TCP_Port = 300
Listening_IP = "127.0.0.1"
BUFFER_SIZE = 64
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # IPv4, TCP
sock.bind((Listening_IP, Listening_TCP_Port))
while True:
sock.listen(1)
conn, address = sock.accept()
print "TCP connection from", address
data = conn.recv(BUFFER_SIZE)
print "Mesage: ", data
conn.close()
# END TCPListen() FUCNTION
# main function
def main():
ThreadUDP = Thread(target=UDPListen)
ThreadTCP = Thread(target=TCPListen)
print "Starting Server..."
ThreadUDP.start()
ThreadTCP.start()
print "Server Started!"
#END main() FUNCTION
if __name__ == "__main__":
main()
However when I run it in Python 2.7 it throws a wobbly, any ideas where I am going wrong?
For me on Windows it launches fine as it is.
For linux you'll have to run it as root or use sudo
e.g.
sudo python ./yourserver.py
Or else change your port number to 1024 or above.
It's ok that they have the same port number. If it were 2 tcp service though it wouldn't be ok. See here.
Edit:
Given the OP's clarification of the real issue the solution is to use.
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
After creating the sockets. Where sock is your socket name.

Categories