Use telnet to log on to a chat room instance in Python

Source: Internet
Author: User

Use telnet to log on to a chat room instance in Python

This example describes how to use telnet to log on to a chat room in Python. Share it with you for your reference. The details are as follows:

I wrote a simple chat room when I was learning Python at home for a long time. I can use telnet to log in.

Unfortunately, Chinese support is poor, so it is no problem to chat in English.

The function is very simple and should not be as powerful as you think, but you can try it if you are interested.

In addition, What surprised me is that it can run the SL4A Python interpreter on the Android tablet (a few code changes is needed, which seems to be the encoding part, I cannot remember ).

Now this can be run on the PC.

Not much nonsense. Put the Code directly, just a py file, and the comments are messy, and the encoding style is not good (it seems like I am using C-like languages ).

?

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 used 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 used for connecting with client and signing 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 other 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 \ 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 ()

With this server program, you can (the premise of course is that you have installed the Python interpreter). If you do not have a client, how can you start chatting?

The following describes how to start chatting. First, run the file. As you can see, the server is waiting for the client to log on:

The client directly uses the telnet command to log in. Note that the port should be the same as the server. The command is telnet 127.0.0.1 9011. Open the telnet console automatically and enter your own name:

Now you can view the log on message on the console of the server:

Continue to use telnet to log on to another user before chatting:

The function is simple, but it reminds me of the things we had 20 or 30 years ago. Hey hey, it should have been like chatting at that time. We never experienced that fun in this age.

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.