I'm trying to connect with Teltonika device (FMB1xx) with this code:
import socket
port = 12050
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', port))
s.listen(1)
conn, addr = s.accept()
print('Connected by ', addr)
imei = conn.recv(1024)
conn.send('\x01')
while True:
try:
data = conn.recv(1024)
if not data: break
print (data)
except socket.error:
print ("Error Occured.")
break
So far I've figured out that conn.send('\x01') doesn't work as it should, and device don't send the rest of data. There were a few questions like this, but none has a good answer. Here you can find documentation of this device.
It must be encoded and ordered (little-/big-endian) if you sending more then one byte. Use something like this:
conn.send(struct.pack('!L', 1))
About connecting to teltonika gps: https://github.com/Kein1945/GPS_Teltonika_Server/
like #uglymaxweber mentioned you have pack it as integer(four bytes) and on python3 you can use the built in to_bytes.
byteorder is little or big endian and the first parameter is the bytesize.
response = 5
conn.send(response.to_bytes(4, byteorder = 'big'))
Related
I m trying to read data from a GPS device "Telonika FMB204" using a python socket and TCP/IP
all you have to do as setup is to specify the server IP and the port the start my python I found Telonika forum showing data received successfully, I try to test it using my dynamic IP address but I the script shows no data my question is there any way to host the script somewhere ?
link :https://community.teltonika-gps.com/4965/how-to-read-data-from-teltonika-fmb001-with-a-python-script
import socket
port = 3000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', port))
s.listen(1)
conn, addr = s.accept()
print('Connected by ', addr)
imei = conn.recv(1024)
conn.send('\x01')
while True:
try:
data = conn.recv(1024)
if not data:
break
f = open("demofile2.txt", "a")
f.write(data)
f.close()
print(data)
except socket.error:
print("Error Occured.")
break
Receiving data from GPS Device will work only on computer with a fixed IP address (you can use no-ip service and open port on your router in my case the port 3000 ) or you can buy a VPS server open the port and you are ready to go
hope those informations will help ;)
When trying to send a file with sockets from one device on my network to another it is throttling the data to 2760 bytes and not receiving the whole file on the server side
Here is the code of my server on my raspberry pi:
import socket
import os
host = "my_ip"
port = "my_port"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen()
def send(mess):
con.send(bytes(mess, "utf-8"))
def receive():
global message
message = con.recv(22000).decode('utf-8')
while True:
try:
con, address = s.accept()
print(f"Connection to {address} made successfully")
receive()
if message == "quit":
break
else:
send("received")
print(len(message))
with open("file.py", 'w', encoding='utf-8')as a:
a.write(message)
os.system("python3 file.py")
except:
pass
And here is the code of my client on another device
with open('file.py', 'r', encoding = 'utf-8')as f:
python_file = f.read()
print(len(python_file))
#returns 20940
import socket
host = "my_ip"
port = my_port
def send(mess):
s.send(bytes(mess, 'utf-8'))
def receive():
message = s.recv(1024).decode('utf-8')
print(message)
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
send_it = input("Send File?[y/n]: ")
if send_it == "y":
try:
s.connect((host, port))
send(python_file)
recieve()
except:
pass
if send_it == "quit":
try:
s.connect((host, port))
send(send_it)
recieve()
except:
pass
else:
pass
When i take off the try loop it doesn't give any errors or reason as to why im only receiving part (2760 bytes) of the file. Also it will randomly(rarely) send more than 2760 bytes or it will sometimes send all the bytes. Its pretty consistently only sending 2760 bytes though.
Maybe you want to use sendall() instead of send(). Basically sendall() guarantees that all data will be sent unless an exception is raised and it's a python feature that is offered by other high level languages as well.
In order to receive all bytes sent, it's a good idea to do that using a loop:
data = bytearray(1)
# loop until there is no more data to receive.
while data:
data = socket.recv(1024) # Receive 1024 bytes at a time.
There is a well explained answer on what the difference between send() and sendall() is in python here.
I want to set up a simple echo server that just echoes back whatever the client sends to it. However, currently the server disconnects (the server socket closes) after it echoes back the first client message. I want to be able to "chat" continuously with the server, where the server just echoes back several consecutive messages I send without disconnecting; e.g.:
"Hi there!"
"Echoing: Hi there!"
"How are you?"
"Echoing: How are you?"
"Cheers!"
"Echoing: Cheers!"
etc.
Currently I have the following code:
server.py:
import socket
HOST = '127.0.0.1'
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
client.py:
import socket
HOST = '127.0.0.1'
PORT = 5000
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('Echoing: ', repr(data))
The server, however, disconnects after it echoes back the first client message (probably because of the if not data: break statement).
P.S. I'd appreciate any additional explanations which might be necessary - this example has educational purposes, so I'm not (only) after getting the code running.
Thanks!
server.py:
import socket
HOST = '127.0.0.1'
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
while True:
data = conn.recv(1024)
if data.decode() == "bye":
break
conn.sendall(data)
conn, addr = s.accept()
I will show you the code I created then talk you through it:
Server:
import socket
HOST = '127.0.0.1'
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
while True:
data = conn.recv(1024)
conn.sendall(data)
For the server I removed:
if not data:
break
It simply wasn't working for me. If you know your message is going to be less than the 1024 bytes( which here it is) it's unnecessary. But if you want a longer message change that value to a bigger number to accommodate. So yes you were right in suspecting it was that line.
Client:
import socket
HOST = '127.0.0.1'
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print("Connected")
while True:
print("Sending data")
s.sendall(b'Hello, world')
print("Recieving data")
data = s.recv(1024)
print('Echoing: ', repr(data))
For the client side I just added the send and receive process into a loop.
Things to note:
This only works for me when run through the terminal, I don't know if you know how to do that so sorry if you do, here's a link explaining:
https://www.wikihow.com/Use-Windows-Command-Prompt-to-Run-a-Python-File
I assumed you use Windows.
You will need to follow the process for both your client.py programme and server.py programme. Make sure you run the server.py programme first.
This will cause an infinite loop of sending and receiving. Press Ctrl+C to terminate.
I hope this solves your problem and you can edit the code accordingly. Any further problems please do comment and I'll try to get back to you.
Maybe use sleep instead of break
if not data:
time.sleep(1)
continue
You have to import time module for this.
Greetings and apologies in advance if it looks a real novice question. I am new to python, or programming for that matter. I am writing a code that sends data from client to server. The data I need to send is from an csv file, which has around 10,000 rows. Currently I am sending the data in a large buffer as a whole, but I would prefer to send it row by row and also receive it the same way. I am not sure if I should use the split() function or there are any better ways to do the same thing.
The client...
import socket
HOST = 'server IP'
PORT = 42050
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
f = open('csvfile.csv', 'rb')
l = f.read(409600)
while True:
print l
s.send(l)
break
f.close()
print "Done Sending"
s.close()
The server...
import socket
HOST = 'local IP'
PORT = 42050
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
print "Server running", HOST, PORT
s.listen(5)
conn, addr = s.accept()
print'Connected by', addr
while True:
data = conn.recv(409600)
print repr(data)
if not data: break
print "Done Receiving"
conn.close()
Thanks in advance for the help.
im not sure what your question actually is ... but its pretty easy to send and receive lines
#client.py
for line in open("my.csv"):
s.send(line)
#server.py
def read_line(sock):
return "".join(iter(lambda:sock.recv(1),"\n"))
iter(lambda:sock.recv(1),"\n")
is essentially the same as
result = ""
while not result.endswith("\n"): result += sock.recv(1)
Trying to create my first client-server application, I came across an error. This code is exactly the same as in the documentation, but I have problems.
Server:
import socket
HOST = 'localhost'
PORT = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while True:
data = conn.recv(1024)
if not data: break
print data
conn.close()
Client:
import socket
HOST = 'localhost'
PORT = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
s.close()
After execution, I don't see the message print Connected by, addr and print data in the server part.
I use Windows 7, Komodo Firewall (I tried to close the firewall, but it didn't solve the problem), Avast Antivirus, Python 2.7.
Very interesting, that there are no errors, but the output just doesn't work.
Also, my server application just freezes until the client connects to the server. Can this be solved just using threading?
Thanks in advance.
You need to accept() and print inside the loop. (or use two loops). I'm not very familiar with socket programming in Python but I'm guess it would look something like this. (completely untested!)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True:
conn, addr = s.accept()
print 'Connected by', addr
while True:
data = conn.recv(1024)
if not data:
break
print data
conn.close()
+1 to Cfreak. Basically what is happening with data is that it is getting assigned an empty string which causes the loop to break. So putting the print statement in the loop fixes the problem. Assuming you need to access that data after the loop terminates try something like
data = []
while True:
datum = conn.recv(1024)
data.append(datum)
if not datum: break
print " ".join(data)
Here is the code I am running and my computer, and it works
client
import socket
HOST = 'localhost'
PORT = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
s.close()
server
import socket
HOST = 'localhost'
PORT = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
data = []
while True:
datum = conn.recv(1024)
data.append(datum)
if not datum: break
print " ".join(data)
conn.close()
so I don't think it is a problem with your code... if you have a machine without a firewall/antivirus on it try the program on that machine.