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.close()
while 1:
conn, addr = s.accept()
start_new_thread(clientthread ,(conn,))
s.close()
With this code every user can send and recive messages. For example if there are 2 users (2 clients with server active): max and paul; if max writes paul>hello paul recives max>hello.
Program uses dictionary and lists for send message to particular client. I don't know if this way is correct.