I've made a code which is able to receive data from the port over TCP protocol. I receive data from ESP8266 every 15 minutes, and then ESP goes to a deepSleep mode. How to change it to make it work continuosly? I wanted to create a new connection in while loop, but it doesn't work.
My code
import sys
import socket
TCP_IP = '192.168.42.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024
param = []
i=0
#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.bind((TCP_IP,TCP_PORT))
#s.listen(1)
#print 'Listening for client...'
#conn, addr = s.accept()
#print 'Connection address:', addr
while 1:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)
print 'Listening for client...'
conn, addr = s.accept()
print 'Connection address:', addr
data = conn.recv(BUFFER_SIZE)
if data == ";" :
conn.close()
print "Received all the data"
i=0
for x in param:
print x
#break
elif data:
print "received data: ", data
param.insert(i,data)
i+=1
#print "End of transmission"
EDIT:
My code after modification.
import sys
import socket
TCP_IP = '192.168.42.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024
param = []
i=0
#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.bind((TCP_IP,TCP_PORT))
#s.listen(1)
#print 'Listening for client...'
#conn, addr = s.accept()
#print 'Connection address:', addr
while 1:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)
while 1:
print 'Listening for client...'
conn, addr = s.accept()
print 'Connection address:', addr
data = conn.recv(BUFFER_SIZE)
if data == ";" :
conn.close()
print "Received all the data"
i=0
for x in param:
print x
#break
elif data:
print "received data: ", data
param.insert(i,data)
i+=1
#print "End of transmission"
s.close()
I created second while loop. I can listen continuously now, but I receive only one packet from the ESP (ESP send 9 packets). How to solve that issue?
If you want to continuously listen for connections and data from your remote end, you can achieve this using select()
A modified version of your code that uses select() is shown below. This will also handle the remote end closing the connection:
import sys
import socket
import select
TCP_IP = '127.0.0.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024
param = []
print 'Listening for client...'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((TCP_IP,TCP_PORT))
server.listen(1)
rxset = [server]
txset = []
while 1:
rxfds, txfds, exfds = select.select(rxset, txset, rxset)
for sock in rxfds:
if sock is server:
conn, addr = server.accept()
conn.setblocking(0)
rxset.append(conn)
print 'Connection from address:', addr
else:
try:
data = sock.recv(BUFFER_SIZE)
if data == ";" :
print "Received all the data"
for x in param:
print x
param = []
rxset.remove(sock)
sock.close()
else:
print "received data: ", data
param.append(data)
except:
print "Connection closed by remote end"
param = []
rxset.remove(sock)
sock.close()
NB I've replaced your IP address with the loopback but you get the idea.
Hope this may be helpful.
Related
I tried programming a simple console menu which sends the string "screenshot" to the client if I press 1 and so on. Now when I press 1 it stops working and if I press Ctrl+C it just sends empty bytes (b' ').
Here is my Server:
import socket
s = socket.socket()
print ("Socket successfully created")
port = 2345
host = '0.0.0.0'
print ("socket binded to %s" %(port))
s.listen(5)
print ("socket is listening")
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)
choice = input('Choice: ')
if choice == 1:
conn.sendall("screenshot")
s.close()
break
And here the client:
import socket
s = socket.socket()
port = 2345
host = 'xxx.xx.xx.xxx'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
data = s.recv(1024)
print('Received', data)
What can I try next?
I can send my data through CSV file. First, write my random numbers into CSV file then send it, but is it possible to send it directly?
my socket code:
import socket
host = 'localhost'
port = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
while True:
print('\nListening for a client at',host , port)
conn, addr = s.accept()
print('\nConnected by', addr)
try:
print('\nReading file...\n')
while 1:
out = "test01"
print('Sending line', line)
conn.send(out)
except socket.error:
print ('Error Occured.\n\nClient disconnected.\n')
conn.close()
spark streaming code:
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
sc = SparkContext("local[2]","deneme")
ssc = StreamingContext(sc, 10)
socket_stream = ssc.socketTextStream("localhost",8080)
random_integers = socket_stream.window( 30 )
digits = random_integers.flatMap(lambda line: line.split(" ")).map(lambda digit: (digit, 1))
digit_count = digits.reduceByKey(lambda x,y:x+y)
digit_count.pprint()
ssc.start()
This is because socket blocks sending the data and never moves on. The most basic solution is to send some amount of data and close the connection:
import socket
import time
host = 'localhost'
port = 50007
i = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
try:
while True:
conn, addr = s.accept()
try:
for j in range(10):
conn.send(bytes("{}\n".format(i), "utf-8"))
i += 1
time.sleep(1)
conn.close()
except socket.error: pass
finally:
s.close()
To get something more interesting check non-blocking mode with timeouts.
I coded chatting program with socket module.
(Python)
and I saw perfect send and get data.
But I found a problem.
This is my Server.py
import socket
import threading
HOST = '127.0.0.1'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print(addr)
def sendmsg():
while True:
data = input()
data = data.encode("utf-8")
conn.send(data)
conn.close()
def getmsg():
while True:
data = conn.recv(1024)
if data is None:
break
else:
data = data.decode("utf-8", "ignore")
print(data)
conn.close()
threading._start_new_thread(sendmsg, ())
threading._start_new_thread(getmsg, ())
while True:
pass
Just on Client can connect with server.
I want to make multiple connection.
So I changed value of s.listen(1) to s.listen(2)
but It doesn't work.
Help me TT
This is client.py
import socket
import threading
HOST = "127.0.0.1"
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
def sendMsg():
while True:
data = input()
s.sendall(str.encode(data))
s.close()
def getMsg():
while True:
data = s.recv(1024)
data = data.decode("utf-8")
print(data)
s.close()
threading._start_new_thread(sendMsg, ())
threading._start_new_thread(getMsg, ())
while True:
pass
Thank you.
In socket, I found that if server does not send any message before call recv(), server will be no response, whatever using mutilthread or not.
As the figure shows below:
enter image description here
enter image description here
server.py(Using SocketServer module):
def handle(self):
conn = self.request
# conn.send('Welcome to server')
flag = True
while flag:
data = conn.recv(1024)
print 'client:' + data
if data == 'exit':
flag = False
conn.send('AAAAAA')
conn.close()
client.py:
client = socket.socket()
ip_port = ('127.0.0.1', 11111)
client.connect(ip_port)
while True:
data = client.recv(1024)
print 'server:' + data
send = raw_input('client:')
client.send(send)
if send == 'exit':
sys.exit()
I would appreciate it very much if you would help me with it.
# server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
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 "Server received data:", data
conn.send("Data received at server side")
conn.close()
# client.py
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)
print "Client: " + MESSAGE
data = s.recv(BUFFER_SIZE)
s.close()
print data
I think providing a sample code could speak itself.
# Expected input:
python server.py
python client.py
# Expected output:
# (server output)
Connection address: ('127.0.0.1', 62136)
Server received data: Hello World!
# (client output)
Client: Hello World!
Data received at server side
You could find out your missing component by comparing the code,such as bind().
Hope it help.
With reference to this site: https://wiki.python.org/moin/TcpCommunication
I got problems with making a Python socket server receive commands from a Python socket client. The server and client can send text to each other but I can't make text from the client trigger an event on the server. Could any one help me? I'm using Python 3.4.
server.py
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes: break
data = databytes.decode('utf-8')
print("Recieved: "+(data))
response = input("Reply: ")
if data == "dodo":
print("hejhej")
if response == "exit":
break
conn.sendall(response.encode('utf-8'))
conn.close()
In server.py I tried to make the word "dodo" trigger print("hejhej").
client.py
import socket
host = '127.0.0.1'
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected to "+(host)+" on port "+str(port))
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
while True:
data = s.recv(1024)
print("Recieved: "+(data.decode('utf-8')))
response = input("Reply: ")
if response == "exit":
break
s.sendall(response.encode('utf-8'))
s.close()
Everything here works fine but, maybe not the way you want it to. If you switch the order on a couple of the lines it will display your event string before you enter your server response.
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes: break
data = databytes.decode('utf-8')
print("Recieved: "+(data))
if data == "dodo": # moved to before the `input` call
print("hejhej")
response = input("Reply: ")
if response == "exit":
break
conn.sendall(response.encode('utf-8'))
conn.close()