HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Private client-server chat

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
serverclientchatprivate

Problem

I try to create a private chat with Python but I don't know best practice.

It's only for study purpose, I'd like understand the logic behind a simple private chat with socket and the best mode to implement it with no framework.

For now, It's not important to check for example if username has > or other, only socket procedure and send messages to specific client.

This is my code for client:

import socket
from thread import *
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8889))
u = raw_input('Username: ')
print 'To send: recipient>message'
def se(s):
    while 1:
        s.send(u + '>' + raw_input())
        print s.recv(1024)
def re(s):
    while 1:
        s.send(u + '>show>')
        r = s.recv(1024)
        if r != 'No messages':
            print r
        sleep(0.05)
start_new_thread(se ,(s,))
start_new_thread(re ,(s,))
while 1:
    pass


and server:

```
import socket
from thread import *
import string
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8889))
s.listen(10)
c = {}
def clientthread(conn):
while 1:
data = conn.recv(1024)
e = data.split('>')
if len(e) == 3:
if e[1] == 'show':
try:
m = ''
for i in range(0, len(c[e[0]])):
m = m + c[e[0]][i]
if i != (len(c[e[0]])-1):
m = m + '\n'
if m == '':
data = 'No messages'
else:
data = m
del c[e[0]]
except:
data = 'No messages'
else:
try:
c[e[1]]
except:
c[e[1]] = []
c[e[1]].append(e[0]+'>'+e[2])
data = 'Ok'
else:
data = 'Error'
conn.send(data)
conn.clo

Solution


  • First off, don't use 1 over True in while loops. While 1 works, using True is much clearer.



  • Secondly, you have inconsistent indentation. While in Python 2.x, this doesn't affect much, Python 3.x will throw an error.



  • Never use try-except without a specific error to catch. There could easily be an error that goes un-noticed.



  • Most of your names are okay, but there are some like c, or e that should be clearer. Variable and function names should also be in snake_case, and classes should be in PascalCase. Names like conn should be renamed to something else, like connection, for example.



  • You need more blank lines. There should be two blank lines in between each code block/function/class on the top level.



  • Finally, you should avoid wildcard imports like this: from thread import *. You should either import the entire module, or any classes/functions/variables that you need.



Here's Python's official style guide, PEP8

Context

StackExchange Code Review Q#94628, answer score: 5

Revisions (0)

No revisions yet.