Python實現的使用telnet登陸聊天室執行個體

來源:互聯網
上載者:User

Python實現的使用telnet登陸聊天室執行個體

   本文執行個體講述了Python實現的使用telnet登陸聊天室。分享給大家供大家參考。具體如下:

  前久在家學習Python的時候寫的一個簡單的聊天室,可以使用telnet來登陸。

  遺憾的是現在對中文的支援很差,英文聊天倒是沒什麼問題了。

  功能很簡單的,應該沒有你想象的那麼強大,但是你如果有興趣的話可以試試的。

  另外,讓我驚奇的是它可以在Android的平板上運行SL4A的Python解譯器上運行(需要稍微改幾句代碼,貌似是編碼的那個地方,我記不清了)。

  現在這個是可以在PC上跑起來的。

  廢話不多,直接放代碼了,就一個py檔案而已,而且注釋是亂七八糟的,編碼風格也不好(好神似我在用類C語言的習慣)。

  ?

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

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

# Filename: ChatRoomServer.py

import threading

import datetime

import socket

# a simple log function

def log(lg):

print(lg)

# Chat room server listen thread class, this class is use for listening client login

# when a client request to connect server, this class will start a connect thread

class ServerListenThread(threading.Thread):

def __init__(self, hostname, port, accept):

threading.Thread.__init__(self)

self.hostname = hostname

self.port = port

self.accept = accept

self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

self.sock.bind((hostname, port))

self.sock.listen(0)

log('ServerIp:%s ServerPort:%s waiting for client...'%self.sock.getsockname())

def run(self):

clientid = 1

while True:

client, cltadd = self.sock.accept()

log('a request from Id=%s%s'%('%d Address:'%clientid , cltadd))

if self.accept(clientid, client):

clientid = clientid + 1

# Connect thread class, this class is use for connecting with client and receiving client's message

class ServerConnectThread(threading.Thread):

def __init__(self, clientid, client, encoding, receive, disconnect):

threading.Thread.__init__(self)

self.client = client

self.clientid = clientid

self.encoding = encoding

self.receive = receive

self.disconnect = disconnect

self.clientname = None

self.inputs = self.client.makefile('rb', 0)

self.outputs = self.client.makefile('wb', 0)

def run(self):

self.sendstring('Input your name:')

while True:

string = self.readline()

if string:

string = string.lstrip()

if len(string)>0:

self.receive(self, string)

else:

self.inputs.close()

self.outputs.close()

break

if self.clientname:

self.disconnect(self)

def sendstring(self, string):

self.sendbytes(bytes(string, self.encoding))

def sendbytes(self, bts):

self.outputs.write(bts)

def readline(self):

rec = self.inputs.readline()

if rec:

string = bytes.decode(rec, self.encoding)

if len(string)>2:

string = string[0:-2]

else:

string = ' '

else:

string = False

return string

# Chat room server class, this class is constitute of a listen thread and many connect thread

class ChatRoomServer:

def __init__(self, ip='0.0.0.0', port=9113, encoding='utf-8'):

self.hostname = ip

self.encoding = encoding

self.port = port

self.clients = {}

self.clientnames = {}

def whenconnect(self, clientid, client):

log('a connect with Id=%s%s'%('%d Address:'%clientid , client.getpeername()))

connect = ServerConnectThread(clientid, client, self.encoding, self.whenreceive, self.whenexit)

connect.start()

return True

def whenreceive(self, client, string):

log('frome %d, receive:%s (%d)'%(client.clientid, string, len(string)))

if client.clientname:

if string[0]=='.':

self.handlecmd(client, string[1:])

else:

now = datetime.datetime.now()

sendstring = '%s %s\r\n %s\r\n'%(now, client.clientname, string)

self.sendtoall(sendstring, client)

else:

if self.clientnames.__contains__(string):

client.sendstring('%s is exited!!!\r\n'%string)

else:

client.clientname = string

client.sendstring('Hell, %s!!!\r\n'%client.clientname)

self.addclient(client)

return True

def whenexit(self, client):

self.delclient(client)

return True

def handlecmd(self, client, cmd):

log('cmd: %s'%cmd)

if cmd=='user':

client.sendstring('User list(%d):\r\n'%len(self.clients))

for i in self.clients:

clt = self.clients[i]

client.sendstring(' %d\t%s\r\n'%(clt.clientid, clt.clientname))

else:

client.sendstring('Unknow command: %s:\r\n'%cmd)

def start(self):

serverlisten = ServerListenThread(self.hostname, self.port, self.whenconnect)

serverlisten.start()

def sendtoall(self, string, notfor):

sends = bytes(string, self.encoding)

for i in self.clients:

if not(notfor and notfor.clientid==i):

self.clients[i].sendbytes(sends)

def addclient(self, client):

self.sendtoall('%s logined!!!\r\n'%client.clientname, client)

self.clients[client.clientid] = client

self.clientnames[client.clientname] = client.clientid

def delclient(self, client):

self.sendtoall('%s logouted!!!\r\n'%client.clientname, client)

del self.clients[client.clientid]

del self.clientnames[client.clientname]

# start a chat room server

ChatRoomServer().start()

  有了這個伺服器程式之後就可以了(當然前提是你安裝的Python解譯器),沒有用戶端的,那麼你會問怎麼開始聊天呢?

  下面開始介紹怎麼開始聊天,首先你把這個檔案運行起來,如可以看到伺服器正在等待用戶端登陸了:

  用戶端直接使用telnet命令登陸,注意連接埠應該和伺服器的一樣,命令為:telnet 127.0.0.1 9011,自動開啟telnet控制台,輸入自己的名字吧:

  現在你在看看伺服器端的控制台介面,可以看到記錄了登陸訊息:

  繼續使用telnet登陸另外的使用者之後就可以聊天了:

  功能很簡陋了,不過這讓我想起了二三十年前的事,嘿嘿,那時候應該就是這樣子聊天的了吧,生在這個時代的我們永遠都體會不到那種樂趣了。

  希望本文所述對大家的Python程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.