Hi Folks,
I'm having some issues with an small socket based server I'm writing,
and I was hoping I could get some help.
My code (attached below) us supposed to read an HTTP Post message
coming from a power meter, parse it, and return a proper HTTP 200 Ok
message. The problem is that the socket fails to send the entire
message as one message, creating a fragmented message which the power
meter then fails to read and accept.
Is there any way to force the socket to send the entire message at
once? Am I doing anything wrong? Is there an easier way to implement
this functionality?
Thanks,
Guy Davidson
Code:
# server application to read data from power meter
# listens on port 80
# receives HTTP POST messages
# author: Maria Kazandjieva <ma******@cs.st anford.edu>, Guy Davidson
<gu********@yah oo.com>
# updated: July 7th, 2008: staring to add database writing
functionality
import time
import datetime #datetime for response message
from socket import * #socket module
import DataPacket #local file with data packet class
import library
import MySQLdb
#formats a proper response message
myHost = ""
myPort = 80
#response = "HTTP/1.1 200 OK\r\nDate: Fri, 20 June 2008 20:40:34 GMT\r
\nServer:SING\r \nX-Powered-By: maria\r\nConten t-Length: 7\r
\nConnection:cl ose\r\nContent-Type: text/html\r\n\r\n[0!:20]\n"
#initializing the socket:
s = socket(AF_INET, SOCK_STREAM) # create a TCP socket
s.setsockopt(SO L_SOCKET, SO_REUSEADDR, 1) # allow port reuse? I hope
s.bind((myHost, myPort)) # bind it to the server port
s.listen(50) # allow 50 simultaneous
pending connections
print('Socket initialized')
#intializing the database
db = MySQLdb.connect (host='localhos t', user='powernet' ,
passwd='jplicks ', db='test')
cursor = db.cursor()
print('Database cursor intialized')
while 1:
print('In while 1')
connection, address = s.accept() # connection is a new socket
print('Accepted a connection')
# TODO:
# verify connection is from powernet so we don't get random
connections to port 80
# best way to get the data would be:
# read until we get all the headers
# parse Content header to get length of data
# read for that many additional bytes
while 1:
print('In while 1 2')
data = connection.recv (4096) # receive up to 4K bytes
print('First set of data receieved:')
#print(data)
'''
if data:
print data
#connection.sen d(response) #send response; OK 200 HTTP message
else:
break
'''
if data:
# second read should recieve the rest of the packet
# finding how long the content is
length = data.find('Cont ent-Length: ')
print('Index of "Content-Length" = ' + str(length))
length = int(data[length+16:lengt h+18])
# adding the bytes from the "Content-Type section:"
length += 51
data += connection.recv (length)
print('Second set of data received:')
print(data)
if data:
#print('Found data:')
#print data #print the string data
packet = DataPacket.Data Packet(data) #use the string data to
create a DataPacket object
print(packet) #print the contents of the object, I hope :)
#we have a packet, let's write it to the mysql DB
packet.mysql_in sert(cursor)
#connection.sen d(response) #send response; OK 200 HTTP
message
print('Sending response')
response = library.respons e_message() #get the response message
totalsent = 0 #initialize a variable to track how much we've sent
so far
while totalsent < len(response): #while we haven't sent everything
sent = connection.send (response[totalsent:]) #send whatever we
can starting where we stopped
totalsent += sent #increment the count of how much we've sent.
else:
print('No data')
break
else:
print('No data')
break 7 4015
Guy Davidson wrote:
Hi Folks,
I'm having some issues with an small socket based server I'm writing,
and I was hoping I could get some help.
My code (attached below) us supposed to read an HTTP Post message
coming from a power meter, parse it, and return a proper HTTP 200 Ok
message. The problem is that the socket fails to send the entire
message as one message, creating a fragmented message which the power
meter then fails to read and accept.
Is there any way to force the socket to send the entire message at
once? Am I doing anything wrong? Is there an easier way to implement
this functionality?
I don't have a solution to the problem presented, per se, but you might have
an easier time implementing this if you use SimpleHTTPServe r or
CGIHTTPServer modules. This will take care of all the socket listening,
and a lot of other low-level details.
Hope that helps!
j
On Jul 10, 1:50*pm, Guy Davidson <GDavids...@gma il.comwrote:
Hi Folks,
I'm having some issues with an small socket based server I'm writing,
and I was hoping I could get some help.
My code (attached below) us supposed to read an HTTP Post message
coming from a power meter, parse it, and return a proper HTTP 200 Ok
message. The problem is that the socket fails to send the entire
message as one message, creating a fragmented message which the power
meter then fails to read and accept.
Is there any way to force the socket to send the entire message at
once? Am I doing anything wrong? Is there an easier way to implement
this functionality?
By 'message', do you mean a single IP datagram? In general, the
answer is no. Each call to 'connection.sen d()' will (in general, see
the next paragraph) transmit as much data as will fit into a single IP
datagram, given the current MTU for the transmission circuit. The
fact that you're calling it in a loop indicates that the data being
sent may be larger than will fit into a datagram.
Or, by 'message', do you mean a single TCP segment? Again, the answer
is no. Your network stack will try to make the TCP segments the right
size to fit within a single IP datagram, leading to the same result as
above.
From your description, I get the feeling that your power meter has a
broken network stack, and you're trying to program around it. You
need to repair the meter.
On Jul 10, 12:38*pm, samwyse <samw...@gmail. comwrote:
On Jul 10, 1:50*pm, Guy Davidson <GDavids...@gma il.comwrote:
Hi Folks,
I'm having some issues with an small socket based server I'm writing,
and I was hoping I could get some help.
My code (attached below) us supposed to read an HTTP Post message
coming from a power meter, parse it, and return a proper HTTP 200 Ok
message. The problem is that the socket fails to send the entire
message as one message, creating a fragmented message which the power
meter then fails to read and accept.
Is there any way to force the socket to send the entire message at
once? Am I doing anything wrong? Is there an easier way to implement
this functionality?
By 'message', do you mean a single IP datagram? *In general, the
answer is no. *Each call to 'connection.sen d()' will (in general, see
the next paragraph) transmit as much data as will fit into a single IP
datagram, given the current MTU for the transmission circuit. *The
fact that you're calling it in a loop indicates that the data being
sent may be larger than will fit into a datagram.
Or, by 'message', do you mean a single TCP segment? *Again, the answer
is no. *Your network stack will try to make the TCP segments the right
size to fit within a single IP datagram, leading to the same result as
above.
From your description, I get the feeling that your power meter has a
broken network stack, and you're trying to program around it. *You
need to repair the meter.
Here's the weird thing. I know it should be able to be done.
Let me try and explain in some more depth what I'm trying to do:
The meter sends HTTP Post messages, and expects, as a reply, an HTTP
200/Ok message.
I try to send the following message, using the socket.send() command:
'HTTP/1.1 200 OK\r\nDate: Thu, 10 July 2008 14:07:50 GMT\r\nServer:
Apache/2.2.8 (Fedora)\r\nX-Powered-By: PHP/5.2.4\r\nConten t-Length: 4\r
\nConnection: close\r\nConten t-Type: text/html; charset=UTF-8\r\n\r
\n[0]\n'
However, when I snoop on the packets in wireshark, here's what I see:
HTTP/1.1 200 Ok:
HTTP/1.1 200 OK
Date: Wed, 09 July 2008 14:55:50 GMT
Server: Apache/2.2.8 (Fedora)
X-Powered-By:
Continuation or non-HTTP traffic:
PHP/5.2.4
Content-Length: 4
Connection: close
Content-Type: text/html; charset=UTF-8
[0]
It splits into two packages, which the meter can't read, and the
communication breaks down there.
Any ideas?
Thanks.
En Thu, 10 Jul 2008 18:10:46 -0300, Guy Davidson <GD********@gma il.com>
escribi�:
On Jul 10, 12:38Â*pm, samwyse <samw...@gmail. comwrote:
>On Jul 10, 1:50Â*pm, Guy Davidson <GDavids...@gma il.comwrote:
My code (attached below) us supposed to read an HTTP Post message
coming from a power meter, parse it, and return a proper HTTP 200 Ok
message. The problem is that the socket fails to send the entire
message as one message, creating a fragmented message which the power
meter then fails to read and accept.
From your description, I get the feeling that your power meter has a broken network stack, and you're trying to program around it. Â*You need to repair the meter.
The meter sends HTTP Post messages, and expects, as a reply, an HTTP
200/Ok message.
I try to send the following message, using the socket.send() command:
'HTTP/1.1 200 OK\r\nDate: Thu, 10 July 2008 14:07:50 GMT\r\nServer:
Apache/2.2.8 (Fedora)\r\nX-Powered-By: PHP/5.2.4\r\nConten t-Length: 4\r
\nConnection: close\r\nConten t-Type: text/html; charset=UTF-8\r\n\r
\n[0]\n'
However, when I snoop on the packets in wireshark, here's what I see:
HTTP/1.1 200 Ok:
HTTP/1.1 200 OK
Date: Wed, 09 July 2008 14:55:50 GMT
Server: Apache/2.2.8 (Fedora)
X-Powered-By:
Continuation or non-HTTP traffic:
PHP/5.2.4
Content-Length: 4
Connection: close
Content-Type: text/html; charset=UTF-8
[0]
It splits into two packages, which the meter can't read, and the
communication breaks down there.
Any ideas?
As Guy Davidson has already pointed out, this is a problem in the meter
TCP implementation, and you should ask the vendor to fix it. (Anyway,
looks like "somewhere" there is a buffer size of 100 bytes or so, very
small).
As a workaround, try to shorten your HTTP response; I guess the Server and
X-Powered-By headers are not required; the Date probably isn't either; and
if all your responses are like "[0]" a simple "Content-Type: text/plain"
may suffice (the meter might just ignore it, anyway).
--
Gabriel Genellina
On Jul 10, 4:10*pm, Guy Davidson <GDavids...@gma il.comwrote:
I try to send the following message, using the socket.send() command:
'HTTP/1.1 200 OK\r\nDate: Thu, 10 July 2008 14:07:50 GMT\r\nServer:
Apache/2.2.8 (Fedora)\r\nX-Powered-By: PHP/5.2.4\r\nConten t-Length: 4\r
\nConnection: close\r\nConten t-Type: text/html; charset=UTF-8\r\n\r
\n[0]\n'
However, when I snoop on the packets in wireshark, here's what I see:
HTTP/1.1 200 Ok:
HTTP/1.1 200 OK
Date: Wed, 09 July 2008 14:55:50 GMT
Server: Apache/2.2.8 (Fedora)
X-Powered-By:
Continuation or non-HTTP traffic:
PHP/5.2.4
Content-Length: 4
Connection: close
Content-Type: text/html; charset=UTF-8
[0]
It splits into two packages, which the meter can't read, and the
communication breaks down there.
OK, it looks like a single TCP segment is being sent by you (which is
consistent with only one socket.send() command being needed), but
something along the way to the meter is using an MTU (Maximum
Transmission Unit) of about 100 bytes, producing two IP datagrams.
How many hops are there between the PC and the meter? Are you
sniffing on the same subnet as the PC, the meter, or somewhere in
between? MTU is normally set to about 1500 (and MSS is generally
MTU-40), but you can generally change these values.
You should be able to set the do-not-fragment flag on your IP packets,
but that may cause them to get dropped instead of sent. You could
also try setting a smaller ICP MSS (Maximum Segment Size), which the
meter might be able to assemble, even if it can't handle fragmented IP
datagrams. Try http://www.cisco.com/en/US/tech/tk87...html#prob_desc
for more help.
You really need to get a networking guru involved if you want to go
down this path. I used to be one, but that was years ago. Or, you
can take Gabriel Genellina's advice and try coding smaller responses.
On Jul 11, 3:46*am, "Gabriel Genellina" <gagsl-...@yahoo.com.a r>
wrote:
As Guy Davidson has already pointed out, this is a problem in the meter *
TCP implementation, and you should ask the vendor to fix it.
That would have been me, not Guy.
En Mon, 14 Jul 2008 17:46:12 -0300, samwyse <sa*****@gmail. comescribió:
On Jul 11, 3:46*am, "Gabriel Genellina" <gagsl-...@yahoo.com.a r>
wrote:
>As Guy Davidson has already pointed out, this is a problem in the meter
That would have been me, not Guy.
Indeed, sorry the misattribution!
--
Gabriel Genellina This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Pete |
last post by:
I've run into an interesting memory problem. I think I'm running out of
heap space, but I'm not sure....
I'm creating two new arrays like such....
pImage = new UBYTE ;
pImageTemp = new UBYTE ;
where nImageSize = 262144. new is NOT returning NULL at this point, which
gives me the impression that new succeeded.
|
by: Mark Anderson |
last post by:
Sorry if this is a rookie mistake... I've been through all the FAQs and the
books I have but I can't see the mistake so I guess it's something simple
<g> - I'm an occasional JS user.
I've got some code (in an external JS file) attached to a number of links
off a query result page. The code it checks if there are any ticked items on
the page and adds them to a lightbox (cart) before going the next called
result page. The idea is to stop...
|
by: Dave |
last post by:
Hello all,
Can anybody help with the problem below? I'm trying to define a conversion
function that converts objects to function pointers and am getting a compile
error on the line indicated below. The compiler interprets this is a
function returning a function, which, of course is illegal... What is the
correct syntax to accomplish this?
Thanks,
Dave
|
by: BBFrost |
last post by:
We just recently moved one of our major c# apps from VS Net 2002 to VS Net
2003. At first things were looking ok, now problems are starting to
appear.
So far ...
(1) ComboBox.SelectedValue = db_value;
If the db_value was not included in the ComboBox value list the
ComboBox.SelectedIndex used to return -1, Now the very same code is
|
by: Railinc |
last post by:
Hi...
I'm trying to write a web service client and am running into a problem with
getting a response back from the server. I know that a full xml message is
being returned (thanks to a tcp/ip sniffer) but in VS.NET all I get is a null
reference.
The server is a java program running on websphere. The provider of the web
service has gotten a websphere client and an apache axis client to work
correctly, so I don't think it's a problem...
| |
by: Doug Lerner |
last post by:
I'm working on a client/server app that seems to work fine in OS Firefox and
Windows IE and Firefox.
However, in OS X Safari, although the UI/communications themselves work
fine, if the characters getting sent back and forth are in Japanese they
come back from the server "moji bake" (corrupted).
Anybody have any ideas why this might work differently in Safari than in
Firefox or IE?
|
by: Steve Smith |
last post by:
I have written a winforms application that launches approximately 150
threads with
Thread.ThreadStart()
Each thread uses CDO 1.21 to logon to a different Exchange mailbox and
send/receive a number of mail messages, reporting back to the UI thread
through the use of a Queue object. When all messages that are expected have
been received, each thread sends a final update to the UI and the method
should exit, which should terminate the...
|
by: Chuck Faranda |
last post by:
I'm trying to debug my first C program (firmware for PIC MCU). The problem
is getting serial data back from my device. My get commands have to be sent
twice for the PIC to respond properly with the needed data. Any ideas?
Here's the code in question, see any reason why a command would not trigger
the 'kbhit' the first time a serial command is sent?: Thanks!
Chuck
****************************************************
while(1) //...
|
by: connyledin |
last post by:
Im trying to create a version of the game Wumpus. Mine is called
Belzebub. But im STUCK! And its due tuesday 2 maj. Im panicing! Can
some one help me??
here is the file:
http://esnips.com/webfolder/b71bfe95-d363-4dd3-bfad-39999a9e36d0
What i have the biggest problems with now is between line 8 and 23.
How i can move the character trough the game. Other parts of the game
that have with the movement to do is between line 83-114 and...
|
by: Frank |
last post by:
Hi,
imagine there's a WEB application reading data from an Oracle database
to visualize in using DataGrids in the clients browser. Yes, sounds
simple, just create OracleConnection + OracleCommand + DataAdapter,
bind a DataGrid to the DataAdapter, that's it.
Problem with that approach might be the hardcoded CommandString of the
OracleCommand. Whenever somebody requests query string changes you have
to adapt the C# code, to recompile and...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |