I am kinda stuck for my project & I desperately need help. I need a simple TCP server python code that has features like logging & time stamp which I could use for my Raspberry Pi. Its for my Final Year Project.
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 ))
We can log the timestamp to the console with the logging module easily by adjusting the basic configuration. import logging logging. basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') logging.info('Message for the user.
To add logging to a file with timestamps, you could use logging
module:
import logging
logging.basicConfig(level=logging.INFO,
filename='myserver.log', # log to this file
format='%(asctime)s %(message)s') # include timestamp
logging.info("some message")
If you run the code; you should see in myserver.log
(+/- your timezone and current time):
2013-12-24 09:20:17,739 some message
Here's a complete example of TCP server that prepends each received line from a client with "Sent by Client: "
phrase and sends it back:
#!/usr/bin/env python
import logging
import sys
from SocketServer import ThreadingTCPServer, StreamRequestHandler
info = logging.getLogger(__name__).info
class EchoLineHandler(StreamRequestHandler):
def handle(self):
info("handling request from %s", self.client_address)
# prepend each line (b'\n') and send it back
for line in self.rfile:
self.wfile.write(b"Sent by Client: ") # assume ascii-based encoding
self.wfile.write(line)
info("done %s", self.client_address)
def test(ServerClass=ThreadingTCPServer, HandlerClass=EchoLineHandler):
# configure logging
logging.basicConfig(level=logging.INFO,
filename='server.log', # log to this file
format='%(asctime)s %(message)s') # include timestamp
# parse command line arguments
host, port = 'localhost', 8826
if len(sys.argv) > 1:
host_, separator, port_ = sys.argv[1].rpartition(":")
port = int(port_)
if separator: # if ":" in sys.argv[1]
host = host_ # accept any host, including empty
# listen for connections
server = ServerClass((host, port), HandlerClass)
info("Serving on %s port %s", *server.server_address)
try:
server.serve_forever()
finally:
info("quit.")
if __name__=="__main__":
test()
To run the server if the code is save in echo_line_server.py
:
$ python -mecho_line_server localhost:8826 & tail -F server.log
2013-12-24 17:09:38,089 Serving on 127.0.0.1 port 8826
To run a client:
$ echo abc | nc localhost 8826
Sent by Client: abc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With