Home Backend Development Python Tutorial python virtual tea party effect

python virtual tea party effect

Apr 09, 2018 am 11:58 AM
python Effect

This time I will bring you the effect of the python virtual tea party. What are the precautions for the effect of the python virtual tea party? The following is a practical case, let’s take a look.

When learning and using almost any

programming language, there is never a shortage of socket exercises, especially when it comes to writing about local area network communications. So this project in the book is just right for practicing socket programming.

The overall idea of ​​this exercise is to first have a chat server. The main functions of this server are to provide client socket connections, store the connection session of each client, process the messages sent by each connection, and parse the client. sent data. That's it. As for the client, you don't need to write code, just use the system's telnet tool.

I think with the above analysis, there is nothing much to say about the rest of this program, except of course the two classes that encapsulate sockets.

I tried this by using the socket class in python and wrote a simple communication program. However, for some reason, accidents always occurred during communication. This simple code is as follows:

server.py

1

2

3

4

5

6

7

8

9

import socket

mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

mysocket.bind(('',8888))

mysocket.listen(5)

while True:

    connection,addr = mysocket.accept()

    revStr = connection.recv(1024)

    connection.send('Server:' + revStr)

    connection.close()

Copy after login
clinet.py

1

2

3

4

5

6

7

8

9

import socket

import time

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

clientsocket.connect(('',8888))

while True:

    time.sleep(2)

    clientsocket.send('hello the5fire')

    print clientsocket.recv(1024)

clientsocket.close()

Copy after login
The reason why this program went wrong is not explained in detail, because python provides two Encapsulated classes to complete the socket communication process: async_chat in asynchat, dispatcher in asyncore and asyncore itself. The former class is used to handle each session between the client and the server, and the latter class is mainly used to provide socket connection services. And each socket connection is hosted by the former (async_chat) for processing.

Look at the code:

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

from asyncore import dispatcher

from asynchat import async_chat

import socket, asyncore

PORT = 5005

NAME = 'TestChat'

class EndSession(Exception):pass

class CommandHandler:

    def unknown(self, session, cmd):

        session.push('Unknown command: %s\r\n' % cmd)

    def handle(self, session, line):

        if not line.strip(): return

        parts = line.split(' ',1)

        cmd = parts[0]

        try: line = parts[1].strip()

        except IndexError: line = ''

        meth = getattr(self, 'do_'+cmd, None)

        try:

            meth(session, line)

        except TypeError:

            self.unknown(session,cmd)

class Room(CommandHandler):

    def init(self, server):

        self.server = server

        self.sessions = []

    def add(self, session):

        self.sessions.append(session)

    def remove(self, session):

        self.sessions.remove(session)

    def broadcast(self, line):

        for session in self.sessions:

            session.push(line)

    def do_logout(self, session, line):

        raise EndSession

class LoginRoom(Room):

    def add(self,session):

        Room.add(self,session)

        self.broadcast('Welcome to %s\r\n' % self.server.name)

    def unknown(self, session, cmd):

        session.push('Please log in \nUse "login"\r\n')

    def do_login(self, session, line):

        name = line.strip()

        if not name:

            session.push('Please enter a name\r\n')

        elif name in self.server.users:

            session.push('The name "%s" is taken.\r\n' % name)

            sessoin.push('Please try again.\r\n')

        else:

            session.name = name

            session.enter(self.server.main_room)

class ChatRoom(Room):

    def add(self, session):

        self.broadcast(session.name + ' has entered the room.\r\n')

        self.server.users[session.name] = session

        Room.add(self, session)

    def remove(self, session):

        Room.remove(self, session)

        self.broadcast(session.name + ' has left the room.\r\n')

    def do_say(self, session, line):

        self.broadcast(session.name + ': ' + line + '\r\n')

    def do_look(self, session, line):

        session.push('The following are in this room:\r\n')

        for other in self.sessions:

            session.push(other.name + '\r\n')

    def do_who(self, session, line):

        session.push('The following are logged in:\r\n')

        for name in self.server.users:

            session.push(name + '\r\n')

class LogoutRoom(Room):

    def add(self, session):

        try: del self.server.users[session.name]

        except KeyError: pass

class ChatSession(async_chat):

    def init(self, server, sock):

        async_chat.init(self,sock)

        self.server = server

        self.set_terminator('\r\n')

        self.data = []

        self.name = None

        self.enter(LoginRoom(server))

    def enter(self, room):

        try

            cur = self.room

        except AttributeError: 

            pass

        else: cur.remove(self)

        self.room = room

        room.add(self)

    def collect_incoming_data(self, data):

        self.data.append(data)

    def found_terminator(self):

        line = ''.join(self.data)

        self.data = []

        try: self.room.handle(self, line)

        except EndSession:

            self.handle_close()

    def handle_close(self):

        async_chat.handle_close(self)

        self.enter(LogoutRoom(self.server))

class ChatServer(dispatcher):

    def init(self, port, name):

        dispatcher.init(self)

        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)

        self.bind(('',port))

        self.listen(5)

        self.name = name

        self.users = {}

        self.main_room = ChatRoom(self)

    def handle_accept(self):

        conn, addr = self.accept()

        ChatSession(self,conn)

if name == 'main':

    s = ChatServer(PORT, NAME)

    try: asyncore.loop()

    except KeyboardInterrupt: print

Copy after login
The entire program is divided into the three parts I mentioned at the beginning:

Provides the client’s socket connection: ChatServer class.

Store the connection session of each client and process the messages sent by each connection: ChatSession class. The function of this class is very simple. It accepts data and determines whether there is a terminator. If so, the found_terminator method is called.

Parse the data sent by the client: it is the remaining room-related classes. These classes are used to process the

strings and commands sent by the client, and they are all inherited from CommandHandler.

Final screenshot:

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Perfect solution to python2.7 being unable to use pip

How to read txt files into DataFrame in batches with python Format

The above is the detailed content of python virtual tea party effect. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles