-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_socket.py
More file actions
81 lines (70 loc) · 1.96 KB
/
client_socket.py
File metadata and controls
81 lines (70 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#coding = utf-8
import socket
import threading
import time
global UID
HOST = '127.0.0.1'
PORT = 38557
UID = ''
SUCCESS = 'succeed'
class Receive(threading.Thread):
global UID
def __init__(self, conn):
self.conn = conn
self.is_receiving = True
threading.Thread.__init__(self)
def run(self):
while self.is_receiving:
try:
server_msg = self.conn.recv(65535)
if not len(server_msg):
break
print ''
print server_msg
except Exception, error:
print error
break
def regist_uid(client, uid):
try:
regist_data = '/%s' % uid
client.send(regist_data)
recv_data = client.recv(65535)
print recv_data
if recv_data == SUCCESS:
return True
else:
return False
except Exception, error:
print error
return False
if __name__ == '__main__':
while True:
uid = raw_input('please enter your username:')
try:
my_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_client.connect((HOST, PORT))
if regist_uid(my_client, uid):
UID = uid
break
except Exception, error:
print error
print 'regist failed, try another username'
else:
print 'login succeed, you can start chatting now'
print 'format: DEST_ID, content\n'
receive = Receive(my_client)
receive.start()
while True:
try:
data = raw_input('[%s]' %UID)
if data.strip() == '':
continue
elif data == 'exit':
break
send_data = ','.join([UID, data])
my_client.send(send_data)
print data
except Exception, error:
print error
my_client.shutdown(socket.SHUT_WR)
my_client.close()