0

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 ))
lospejos
  • 1,976
  • 3
  • 19
  • 35
user3128219
  • 9
  • 1
  • 3
  • related: [How to add logging to a file with timestamps to a Python TCP Server for Raspberry Pi](http://stackoverflow.com/q/20695241/4279) – jfs Dec 29 '13 at 22:09

2 Answers2

0

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

dstromberg
  • 6,954
  • 1
  • 26
  • 27
  • Hi , Thank you so much for this code. It kinds of work the way I want it , like how a its saves in a text file , but now , when I debug my code , the black screen will appear , but it will not show the data that is being received , instead it just saves into the text file. Is there a way that I can make it appear in my black pop up screen as well as in the saved text file? My code previously could show the data received on the pop up black screen but after the log features were added , it kind of disappear. Thank you for your help. – user3128219 Dec 23 '13 at 02:47
  • Add to logger(), under the with statement somewhere: sys.stdout.write(string). – dstromberg Dec 23 '13 at 04:26
  • Add to logger() ? As in , inside the def logger? – user3128219 Dec 23 '13 at 06:42
  • At the top of the file, add "import sys". – dstromberg Dec 23 '13 at 18:33
  • Yes, add the sys.stdout.write(string) inside the with statement, which is inside logger. – dstromberg Dec 23 '13 at 18:40
-2

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()
Jeremy Visser
  • 6,237
  • 1
  • 25
  • 30
  • Totally unrelated. The question was clear enough to understand that using " Hercules which acts as my TCP client" is not just writing to files. – dlewin Apr 21 '14 at 16:20