how to define and use multiple sockets in python - python

I want to make a server, which receives messages from smartphones and based on them, sends messages to one specific IP and port. but when I define two IPs (one for the server and another to send messages) gives the error that I cannot use the socket more than ONE time. I am not a programmer, so please help me correct my code.
import socket
import time
host = '192.168.100.41' #Define a server to receive messages
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(1)
c, addr = s.accept()
print ("Connection from: ")
while True:
Buffer = c.recv(1024)
if not data:
break
address = ( '192.168.100.60', 5555) #Defind Destination address to send a message (must match destination IP and port)
client_socket = socket(AF_INET, SOCK_DGRAM) #Set Up the Socket
client_socket.settimeout(1) #only wait 1 second for a resonse
def ON(evt):
data = "1ON" #Set data
client_socket.sendto(data, address) #send command
try:
rec_data, addr = client_socket.recvfrom(2048) #Read response
print (rec_data) #Print the response
except:
pass

Related

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?

UDP Server and Client Failing to Send And Recieve Messages

I am building a simple network chat in Python using UDP, however, when I run the server code on one machine and the client on another, no message is received by the server and no message is sent back to the client by the server script. Here is my code:
Server:
import socket, sys
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 9997)) #need higher port
while True:
x = raw_input("Enter your message: ")
sent = sock.sendto(x, ('', 9997))
data, address = sock.recvfrom(4096)
print data, " ", address
sock.close()
Client:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
print "Waiting to receive"
data, server = sock.recvfrom(4096)
print data
x = raw_input("Enter message: ")
sent = sock.sendto(x, server)
sock.close()
Does anyone know what I am doing wrong here? Is is possible that code is fine, but the UDP is not reliable enough and is dropping the message?
As I said, since your code seems a little unclear (to me, at least), I'm posting you a very similar working example.
Here's the Server:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 1932)
sock.bind(server_address)
BUFFER_SIZE = 4096
try:
while True:
data, address = sock.recvfrom(BUFFER_SIZE)
print "Client sends: ", data
reply = raw_input("Your response:\n")
sock.sendto(reply,address)
except KeyboardInterrupt:
sock.close()
The server creates a socket and binds it to its address and the port it's listening to, 1932 in our case. He waits for an incoming message, asks for a reply, then sends it back to the sender.
Here's the Client:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_address = ('localhost', 1931)
server_address = ('localhost', 1932)
sock.bind(client_address)
BUFFER_SIZE = 4096
try:
first_msg = raw_input("Your first message:\n")
sock.sendto(first_msg,server_address)
while True:
data, address = sock.recvfrom(BUFFER_SIZE)
print "Client sends: ", data
reply = raw_input("Your response:\n")
sock.sendto(reply,address)
except KeyboardInterrupt:
sock.close()
It's very similar to the server, the only difference is that it sends a message before the while loop, in order to start the conversation. Then it just enters the receive/reply loop, just as the server does. It has the server address too, that is different (different port, since I'm on localhost)
The try/catch block is here just to close gracefully the whole process.
I used localhost and different ports on my computer and tested it, and it works. You should just change the addresses to get it working over LAN, and you could keep the same port if the addresses are different, it should work.

Send messages received by server to multiple clients in python 2.7 with socket programming

So I have created a socket program for both client and server as a basic chat. I made it so the server accepts multiple clients with threading, so that is not the problem. I am having trouble sending messages to each client that is connected to the server. I am not trying to have the server send a message it created but rather have client1 sending a message to client2 by going through the server. For some reason it will only send it back to client1.
For example, client1 will say hello and the server will send the same message back to client1 but nothing to client2. I fixed this slightly by making sure the client doesn't receive its own message but client2 is still not receiving the message from the client1.
Any help will be appreciated.
I have tried multiple changes and nothing seems to work. You can look at my code for specifics on how I did things but ask if there are any questions.
Also, there is a question where someone has asked that is similar and I thought it would give me an answer but the responses stopped going through and a solution was never fully given, so please don't just refer me to that question. that is located here: Python 3: Socket server send to multiple clients with sendto() function.
Here's the code:
CLIENT:
import socket
import sys
import thread
#Create a socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Enter username to identify self to others
name = raw_input("Enter username: ") + ": "
#Connect socket to ip and port
host = socket.gethostname()
#host = '192.168.1.10'
server_address = (host, 4441)
sock.connect(server_address)
#function waiting to receive and print a message
def receive(nothing):
while True:
data = sock.recv(1024)
if message != data:
print data
# Send messages
while True:
#arbitrary variable allowing us to have a thread
nothing = (0, 1)
message = name + raw_input("> ")
sock.sendall(message)
#thread to receive a message
thread.start_new_thread(receive, (nothing,))
SERVER:
import socket
import sys
import thread
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
host = socket.gethostname()
server_address = (host, 4441)
sock.bind(server_address)
#Listen for incoming connections
sock.listen(5)
print "Waiting for connection..."
#Variable for the number of connections
numbOfConn = 0
#Name of list used for connections
addressList = []
#Function that continuosly searches for connections
def clients(connection, addressList):
while True:
message = connection.recv(1024)
print message
#connection.sendall(message)
#for loop to send message to each
for i in range(0,numbOfConn - 1):
connection.sendto(message, addressList[i])
connection.close()
while True:
#accept a connection
connection, address = sock.accept()
print 'Got connection from', address
numbOfConn += 1
addressList.append((address))
#Thread that calls the function: clients and stores them in a tuple called connection
thread.start_new_thread(clients, (connection, addressList))
sock.close()
Please help me if you can!
EDIT:
I was able to fix it to a certain extent. It is still a little buggy but I am able to send messages back and forth now. I needed to specify the connection socket as well as the address. Here's the updated code:
SERVER
import socket
import sys
import thread
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
host = socket.gethostname()
server_address = (host, 4441)
sock.bind(server_address)
#Listen for incoming connections
sock.listen(5)
print "Waiting for connection..."
#Variable for the number of connections
numbOfConn = 0
#Name of list used for connections
addressList = []
connectionList = []
#Function that continuosly searches for connections
def clients(connectionList, addressList):
while True:
for j in range(0,numbOfConn):
message = connectionList[j].recv(1024)
print message
#for loop to send message to each
for i in range(0,numbOfConn):
connectionList[i].sendto(message, addressList[i])
connection.close()
while True:
#accept a connection
connection, address = sock.accept()
print 'Got connection from', address
numbOfConn += 1
addressList.append((address))
connectionList.append((connection))
#Thread that calls the function: clients and stores them in a tuple called connection
thread.start_new_thread(clients, (connectionList, addressList))
sock.close()

Python Logging for TCP server

I am having some problems adding in a logging file for my python TCP server code.
I've looked at some examples, but as I don't have much experience in writing my own scripts/codes, I'm not very sure how to go about doing this. I would appreciate if someone could guide me in the right direction with explanation and some examples if possible.
I am using HERCULES SETUP UTILITY , which acts as my TCP client, while my visual studio python code acts as a SERVER. My SERVER can receive the data which is sent by the client by now , I just can't seem to add in a logging file which can save the sent data into text file.Can someone please show me some examples or referance please? Your help would mean alot. This is my code so far :
from socket import *
import thread
BUFF = 1024 # buffer size
HOST = '172.16.166.206'# IP address of host
PORT = 1234 # Port number for client & server to recieve data
def response(key):
return 'Sent by client'
def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF) # receive data(buffer).
print 'data:' + repr(data) #Server to recieve data sent by client.
if not data: break #If connection is closed by client, server will break and stop recieving data.
print 'sent:' + repr(response('')) # respond by saying "Sent By Client".
if __name__=='__main__':
ADDR = (HOST, PORT) #Define Addr
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR) #Binds the ServerSocket to a specific address (IP address and port number)
serversock.listen(0)
while 1:
print 'waiting for connection...'
clientsock, addr = serversock.accept()
print '...connected from:', addr #show its connected to which addr
thread.start_new_thread(handler, (clientsock, addr ))
In context, maybe something like this?
#!/usr/local/cpython-2.7/bin/python
import socket
import thread
BUFF = 1024 # buffer size
HOST = '127.0.0.1'
PORT = 1234 # Port number for client & server to recieve data
def response(key):
return 'Sent by client'
def logger(string, file_=open('logfile.txt', 'a'), lock=thread.allocate_lock()):
with lock:
file_.write(string)
file_.flush() # optional, makes data show up in the logfile more quickly, but is slower
def handler(clientsock, addr):
while 1:
data = clientsock.recv(BUFF) # receive data(buffer).
logger('data:' + repr(data) + '\n') #Server to recieve data sent by client.
if not data:
break #If connection is closed by client, server will break and stop recieving data.
logger('sent:' + repr(response('')) + '\n') # respond by saying "Sent By Client".
if __name__=='__main__':
ADDR = (HOST, PORT) #Define Addr
serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.bind(ADDR) #Binds the ServerSocket to a specific address (IP address and port number)
serversock.listen(0)
while 1:
logger('waiting for connection...\n')
clientsock, addr = serversock.accept()
logger('...connected from: ' + str(addr) + '\n') #show its connected to which addr
thread.start_new_thread(handler, (clientsock, addr))
HTH
It sounds to me like your question would be better rephrased as “How do I read and write files within Python?”.
This is something well documented at: http://docs.python.org/2.7/tutorial/inputoutput.html#reading-and-writing-files
Example:
f = open('/tmp/log.txt', 'a')
f.write('Doing something')
do_something()
f.write('Other stuff')
other_stuff()
f.write('All finished')
f.close()

Categories

Resources