Simple Tcp/ip communication service (python)

2 views
Skip to first unread message

Chris

unread,
Dec 30, 2012, 5:29:16 AM12/30/12
to qda_...@googlegroups.com
Hey, I write a simple tcp/ip communication service using python. But it is not nice. It is not enough stable. So I wanna you guys give some advices to me. Hope your reply.
 
Here is my diagrammatic map:
and here is my python code.
there are two python files.
 
tcp_commFunc.py
 
 #Function for recving message
def RecvMsg(con):
        while 1:
                msg = con.recv(4096)
                print msg

#Function for handling connections. This will be used to create threads
def clientthread(conn):
 #Sending message to connected client
 conn.send('Welcome to the server.\n') #send only takes string
 start_new_thread(RecvMsg ,(conn,))
 #infinite loop so that function do not terminate and thread do not end.
 while True:
                time.sleep(2)
  reMsg = "I see you ."
  print reMsg
  reply = reMsg
  conn.sendall(reply)
 
 #came out of loop
 conn.close()

 
Py_Socket_Server.py
 
 
import socket
import sys
import time
from thread import *
from tcp_commFunc import *
HOST = '192.168.1.3' # Symbolic name meaning all available interfaces
PORT = 8888         # Arbitrary non-privileged port
msg = 'Init..'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
 s.bind((HOST, PORT))
except socket.error , msg:
 print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
 sys.exit()
print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
 conn, addr = s.accept()
 print 'Connected with ' + addr[0] + ':' + str(addr[1])
 
 #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
 start_new_thread(clientthread ,(conn,))
s.close()
Reply all
Reply to author
Forward
0 new messages