-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientEnd.py
More file actions
90 lines (69 loc) · 2.7 KB
/
ClientEnd.py
File metadata and controls
90 lines (69 loc) · 2.7 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
81
82
83
84
85
86
87
88
89
# -*- coding: utf-8 -*-
import socket, sys, select, traceback
from SocketWrapper import *
class Client:
clientSock = None
port = 12354
host = None
RECV_BUFFER = 4096
def __init__(self):
self.host = socket.gethostname()
self.clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__connect()
def __connect(self):
try:
self.clientSock.connect((self.host, self.port))
except:
print "unable to connect server"
else:
self.__mainLoop()
def __closeClient(self):
socketSend(self.clientSock, "CLIENT_SHUTDOWN")
self.clientSock.close()
def __mainLoop(self):
rList = [self.clientSock, sys.stdin]
try:
while True:
readList, writeList, errorList = select.select(rList, [], [])
quitProgram = False
for element in readList:
if element == self.clientSock:
data = socketRecv(self.clientSock, self.RECV_BUFFER)
if not data:
print "this connection is not available"
quitProgram = True
else:
if data == 'server msg: SERVER_SHUTDOWN':
print "server is shut down"
quitProgram = True
break
print data
else:
data = sys.stdin.readline()
# 当 直接从terminal关闭程序的时候,貌似程序并不会抛出异常
# 反之,程序会读取一个空的字符串;此处,我们认为''代表此种情况
# 但是时候有更合理的解决方案?
if data == 'esc\n' or data == '':
quitProgram = True
break
else:
# remove '\n' and append EOD as segmentation sign
socketSend(self.clientSock, data[:-1])
if quitProgram:
self.__closeClient()
break
except KeyboardInterrupt:
print "KeyboardInterrupt"
f = open("keyboard.txt", 'a')
traceback.print_exc(file=f)
f.flush()
f.close()
self.__closeClient()
except SystemExit:
f = open("c:log.txt", 'a')
traceback.print_exc(file=f)
f.flush()
f.close()
self.__closeClient()
if __name__ == "__main__":
client = Client()