0

I have written the a TCP socket program in python where the temperature readings will be sent to a particular IP and port . Here is the code for the client socket program in TCP.

  import time
    import os
    import fnmatch
    import logging
    import socket
    import json
    import sys
    from datetime import datetime

    logging.basicConfig(filename='/home/pi/DS18B20_error.log', level=logging.DEBUG,
                        format='%(asctime)s %(levelname)s %(name)s %(message)s')
    logger=logging.getLogger(__name__)

    os.system('modprobe w1-gpio')
    os.system('modprobe w1-therm')
    HOST,PORT="10.10.1.114",8090
    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.connect((HOST,PORT))
    def postReadingsUDP(id,temperature,currentTime):
            thermalId=str(id)
            temp=str(temperature)
            data={"sensorId":thermalId,"Temperature":temp,"Timestamp":currentTime}
            jsonObj=json.dumps(data)
            sock.send(jsonObj)


    def postTempReadings(IDs, temperature,currentTime):


        for i in range(0,len(temperature)):
            postReadingsUDP(IDs[i],temperature,currentTime)

    #get readings from sensors every 1 sec  and send them to server
    while True:

      temperature = []
      IDs = []

      for filename in os.listdir("/sys/bus/w1/devices"):
       if fnmatch.fnmatch(filename, '28-*'):
          with open("/sys/bus/w1/devices/" + filename + "/w1_slave") as fileobj:
            lines = fileobj.readlines()
            if lines[0].find("YES"):
              pok = lines[1].find('=')
              temperature.append(float(lines[1][pok+1:pok+6])/1000)
              IDs.append(filename)
            else:
              logger.error("Error reading sensor with ID: %s" % (filename))

     if (len(temperature)>0):
            localtime=datetime.now()
            currentTime=str(localtime)
            postTempReadings(IDs,temperature,currentTime)

The server receiver code is in JAVA

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;




public class TcpServerSample {

    public static void main(String argv[]) throws Exception
    {
       String clientSentence;
       ServerSocket welcomeSocket = new ServerSocket(8090);

       while(true)
       {
          Socket connectionSocket = welcomeSocket.accept();
          BufferedReader inFromClient =
             new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
          clientSentence = inFromClient.readLine();
          System.out.println("Received: " + clientSentence+"\n");
       }
    }
}

The problem iam facing is that i cannot receive any data from the client until i stop the client program , it seems the JSON data that was created when the client program was running kept on appending and was sent as a single json data to the server .

The data i expected is that json should be sent in continuosly like below

Received: {"sensorId": "28-041673cb78ff", "Temperature": "[22.75]", "Timestamp": "2016-11-23 10:36:41.038058"}

but the actual data was like all JSON data's were appended and sent as one data.

Received: {"sensorId": "28-041673cb78ff", "Temperature": "[22.75]", "Timestamp": "2016-11-23 10:36:41.038058"}Received: {"sensorId": "28-041673cb78ff", "Temperature": "[22.75]", "Timestamp": "2016-11-23 10:36:41.038058"}Received: {"sensorId": "28-041673cb78ff", "Temperature": "[22.75]", "Timestamp": "2016-11-23 10:36:41.038058"}

6
  • How to detect EOS(End OF STREAM) ? Some socket system using *NULL* but don't see any start-end delimiter. Short comment things WELLCOME TO PROTOCOL WORLD ! Commented Nov 23, 2016 at 5:39
  • Your server need a BUFFER SIZE or a END DELIMITER(End delimiter is best things cos don't wait reaching buffer). Commented Nov 23, 2016 at 5:50
  • can you modify the code above and show me an example on where should i put the delimeter because it seems if i add "\n" by jsonObj=json.dumps(data)+"\n" ,it's not working Commented Nov 23, 2016 at 6:12
  • will be work if add "\n" char python code but how to detect on server side ? Need check whole packet if last incoming element is \n. getInputStream() handle your incoming packet(and my opinion removed \n character ). Need reading Byte mode all incoming message(server side). Commented Nov 23, 2016 at 7:02
  • can u change the mentioned server and client source code so that i can understand it better? Commented Nov 23, 2016 at 13:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.