Super detailed graphic tutorial Aliyun free student ECS cloud server to receive and use the whole process (deploy Python multi-person chat room program)

Foreword:

The Python class needs to complete an experiment that needs to implement a multi-person chat room. An additional requirement is whether chatting is not limited to the local area network, but can be connected to the public network to chat. This requires us to run the server-side Python code on the cloud server.

And because I have never touched this content before, I really encountered a lot of problems in the process, and I also spent a night to complete the deployment and use of cloud servers. In fact, I also checked a lot of cloud server usage tutorials, but most of them are complicated (many are for the deployment of web projects), and none of them are very suitable for my current needs. Hence this beginner's tutorial.

text:

1. Participate in Alibaba Cloud's "Feitian Acceleration Program" to receive 2.5 months of ECS cloud servers for free

1. Participate in the program to obtain qualifications 

The Alibaba Cloud Feitian Acceleration Plan was actually mentioned by my teacher inadvertently in class at the beginning. Later, my roommate discovered this plan when visiting Alibaba Cloud. If you don't know it yet, here is the corresponding link, you can go to one Look:

https://developer.aliyun.com/plan/student Aliyun "Flying Acceleration Plan"


 

 After participating in the program, follow the instructions on the website, complete registration, student certification, complete an experiment (about 15 minutes or so) and a test (very simple, all basic knowledge), and probably proceed to the fourth step . Now, you can get 2 weeks of free ECS cloud server .

2. Configuration of cloud server

At this point, we found that we could finally get the server, but a bunch of strange configurations came up. Fortunately, Alibaba Cloud has already helped us choose most of the configurations. What we can choose is the operating system installed on the cloud server . At this point, I recommend choosing a cloud server with the Windows operating system for newbies. The final interface of the server obtained in this way is basically the same as the interface of win10 , we will also be familiar with it, and it is easy to get started.

It doesn't matter if you choose the wrong one, you can change it at any time after the operating system. Of course, our teacher's opinion is to install the Linux system, which is faster than the Windows system.

 I chose windows server 2019 data center version 64-bit Chinese version

2. Connection and preparation of cloud server

1. Cloud server connection (two connection methods)

After receiving it, you can connect to the server. Not much to say, just go to the picture above

Step1: First open the Alibaba Cloud homepage and log in, open the console, and enter the ECS interface of the cloud server (I don’t know why the picture here is illegal, it should be easy to see)

 Step2: Enter the instance interface 

  Step3: Click on the instance, [if the instance interface is blank, you can adjust the region selection above]

 Step4: After resetting the password, connect remotely. The password here is equivalent to the computer's power-on password, that is, the user login password. After that use VNC to connect remotely

Step5: Connect remotely, enter (or reset) the VNC password, then turn on the computer and enter the login password.

 

 If there are small partners who feel very stuck, they can also use the remote desktop connection that comes with windows to connect to the server. I also recommend this connection method! ! !

Specific connection steps: Enter "Remote Desktop Connection" in the Windows search box, or run the mstsc command with the Win+R key to open the Remote Desktop Connection

The second connection method is as follows

 After entering the login password, you can connect!

2. Cloud server preparation (download a new browser, download the Python configuration environment)

Although the cloud server is the same as our computer, it is really poor and white. There is only an icon of a recycle bin, and the browser can only use IE browser. Let's use a better browser first!

Open the IE browser on the bottom bar of the desktop, first turn on its download switch, otherwise you will not be able to download things

 

Then you can enter the Baidu URL, search for the Chrome browser to install it, and you can also install other browsers you like~ 

 After that, there is the regular configuration of the Python environment. I won't introduce it here. There are many tutorials in this area. In addition, what should I do if I want to quickly upload the contents of my original computer to the cloud server, for example, I think that the Python official website is too slow to download the installation package, and I want to download it on my computer first and then upload it to the server.

3. Learn to use the airdrop website (optional)

If you want to transfer files between two computers , the next QQ may be the first thing that comes to your mind, but this is too slow and wastes resources. Today we will learn to use the airdrop website. The following is the corresponding link

 airportal.cn Airdrop website

In fact, it is to upload the required files here on this machine , obtain the extraction code , and then open the website again on the computer that needs to be downloaded , and enter the extraction code to download. This can also be used when you need to type the code you have typed before when you go to the computer room, you can download your own code file to the computer in the computer room through the airdrop website without downloading other third-party software.

finally! We have completed the initial connection and preparation of the cloud server! ! !

3. Initial experience of using cloud server (take my Python multi-person chat room project as an example)

Friends in need can go to my other blog to see the detailed Python code analysis of this multi-person chat room:

Python writes multi-threaded multi-person chat room system (Socket programming, tkinter component use)

For the sake of speed, put the code of the cloud server version of the server and client here !

Server-side code, you need to modify the IP address to the server's private address (important)

from socket import *
from sqlite3 import connect
import threading
from datetime import *

# 时间格式声明,用于后面的记录系统时间
ISOTIMEFORMAT = '%Y-%m-%d %H:%M:%S'                     

# 设置IP地址和端口号,这里注意要将IP地址换成云服务器自己的私有地址!!!
IP = '127.0.0.1'                 
PORT = 30000

# 用户列表和套接字列表,用于后面给每个套接字发送信息
user_list = []
socket_list = []

# 聊天记录存储至当前目录下的serverlog.txt文件中
try:
    with open('serverlog.txt', 'a+') as serverlog:                    
        curtime = datetime.now().strftime(ISOTIMEFORMAT)
        serverlog.write('\n\n-----------服务器打开时间:'+str(curtime)+',开始记录聊天-----------\n')
except:
    print('ERROR!')


# 读取套接字连接
s = socket()
s.bind((IP, PORT))
s.listen()
def read_client(s, nickname):                           
    try:
        return s.recv(2048).decode('utf-8')                     # 获取此套接字(用户)发送的消息
    except:                                                     # 一旦断开连接则记录log以及向其他套接字发送相关信息
        curtime = datetime.now().strftime(ISOTIMEFORMAT)        # 获取当前时间
        print(curtime)
        print(nickname + ' 离开了聊天室!')
        with open('serverlog.txt', 'a+') as serverlog:          # log记录
            serverlog.write(str(curtime) + '  ' + nickname + ' 离开了聊天室!\n')
        socket_list.remove(s)
        user_list.remove(nickname)
        for client in socket_list:                              # 其他套接字通知(即通知其他聊天窗口)
            client.send(('系统消息:'+ nickname + ' 离开了聊天室!').encode('utf-8'))



# 接收Client端消息并发送
def socket_target(s, nickname):                         
    try:
        s.send((','.join(user_list)).encode('utf-8'))               # 将用户列表送给各个套接字,用逗号隔开
        while True:
            content = read_client(s, nickname)                      # 获取用户发送的消息
            if content is None:
                break
            else:
                curtime = datetime.now().strftime(ISOTIMEFORMAT)    # 系统时间打印
                print(curtime)
                print(nickname+'说:'+content)
                with open('serverlog.txt', 'a+') as serverlog:      # log记录
                    serverlog.write(str(curtime) + '  ' + nickname + '说:' + content + '\n')
                for client in socket_list:                          # 其他套接字通知
                    client.send((nickname + '说:'+ content).encode('utf-8'))
    except:
        print('Error!')

while True:                                                     # 不断接受新的套接字进来,实现“多人”
    conn, addr = s.accept()                                     # 获取套接字与此套接字的地址
    socket_list.append(conn)                                    # 套接字列表更新
    nickname = conn.recv(2048).decode('utf-8')                  # 接受昵称

    if nickname in user_list:                                   # 昵称查重,相同则在后面加上数字
        i = 1
        while True:
            if nickname+str(i) in user_list:
                i = i + 1
            else:
                nickname = nickname + str(i)
                break

    user_list.append(nickname)                                  # 用户列表更新,加入新用户(新的套接字)
    curtime = datetime.now().strftime(ISOTIMEFORMAT)
    print(curtime)
    print(nickname + ' 进入了聊天室!')

    with open('serverlog.txt', 'a+') as serverlog:              # log记录
        serverlog.write(str(curtime) + '  ' + nickname + ' 进入了聊天室!\n')

    for client in socket_list[0:len(socket_list)-1]:            # 其他套接字通知
        client.send(('系统消息:'+ nickname + ' 进入了聊天室!').encode('utf-8'))

    # 加入线程中跑,加入函数为socket_target,参数为conn,nickname
    threading.Thread(target=socket_target, args=(conn,nickname,)).start()

If you don't know the private IP address of the cloud server, you can run cmd on the cloud server (press Win+R to run the cmd command), and the IPv4 address obtained by entering the ipconfig command is the private address of the cloud server we need.

Client code, you need to modify the IP address to the public network address of the cloud server (important):

from tkinter import *
from datetime import *
from socket import *
import threading
import sys
import tkinter
import tkinter.messagebox
from tkinter.scrolledtext import ScrolledText

ISOTIMEFORMAT = '%Y-%m-%d %H:%M:%S'         # 时间格式声明
IP = '127.0.0.1'                            # IP地址,注意这里填云服务器的公网地址不是私有地址!
Port = 30000                                # 端口号
s = socket()                                # 套接字


# 登录窗口
def Login_gui_run():                                            

    root = Tk()
    root.title("小刘聊天系统·登录")          # 窗口标题
    frm = Frame(root)

    root.geometry('300x150')                # 窗口大小

    nickname = StringVar()                                      # 昵称变量

    def login_in():                                             # 登录函数(检查用户名是否为空,以及长度)
        name = nickname.get()                                   # 长度是考虑用户列表那边能否完整显示
        if not name:
            tkinter.messagebox.showwarning('Warning', message='用户名为空!')
        elif len(name)>10:
            tkinter.messagebox.showwarning('Warning', message='用户名过长!最多为十个字符!')
        else:
            root.destroy()
            s.connect((IP, Port))                     # 建立连接
            s.send(nickname.get().encode('utf-8'))              # 传递用户昵称
            Chat_gui_run()                                      # 打开聊天窗口


    # 登录按钮、输入提示标签、输入框
    Button(root, text = "登录", command = login_in, width = 8, height = 1).place(x=100, y=90, width=100, height=35)
    Label(root, text='请输入昵称', font=('Fangsong',12)).place(x=10, y=20, height=50, width=80)
    Entry(root, textvariable = nickname, font=('Fangsong', 11)).place(x=100, y=30, height=30, width=180)

    root.mainloop()


# 聊天窗口
def Chat_gui_run():                                         
    window = Tk()
    window.maxsize(650, 400)                                # 设置相同的最大最小尺寸,将窗口大小固定
    window.minsize(650, 400)

    var1 = StringVar()
    user_list = []
    user_list = s.recv(2048).decode('utf-8').split(',')     # 从服务器端获取当前用户列表
    user_list.insert(0, '------当前用户列表------')


    nickname = user_list[len(user_list)-1]                  # 获取正式昵称,经过了服务器端的查重修改
    window.title("小刘聊天系统--"+nickname)                  # 设置窗口标题,体现用户专属窗口(不是)
    var1.set(user_list)                                     # 用户列表文本设置
    # var1.set([1,2,3,5])
    listbox1 = Listbox(window, listvariable=var1)           # 用户列表,使用Listbox组件
    listbox1.place(x=510, y=0, width=140, height=300)


    listbox = ScrolledText(window)                          # 聊天信息窗口,使用ScrolledText组件制作
    listbox.place(x=5, y=0, width=500, height=300)


    # 接收服务器发来的消息并显示到聊天信息窗口上,与此同时监控用户列表更新
    def read_server(s):
        while True:
            content = s.recv(2048).decode('utf-8')                      # 接收服务器端发来的消息
            curtime = datetime.now().strftime(ISOTIMEFORMAT)            # 获取当前系统时间
            listbox.insert(tkinter.END, curtime)                        # 聊天信息窗口显示(打印)
            listbox.insert(tkinter.END, '\n'+content+'\n\n')
            listbox.see(tkinter.END)                                    # ScrolledText组件方法,自动定位到结尾,否则只有消息在涨,窗口拖动条不动
            listbox.update()                                            # 更新聊天信息窗口,显示新的信息


            # 贼傻贼原始的用户列表更新方式,判断新的信息是否为系统消息,暂时没有想到更好的解决方案
            if content[0:5]=='系统消息:':
                if content[content.find(' ')+1 : content.find(' ')+3]=='进入':
                    user_list.append(content[5:content.find(' ')])
                    var1.set(user_list)
                if content[content.find(' ')+1 : content.find(' ')+3]=='离开':
                    user_list.remove(content[5:content.find(' ')])
                    var1.set(user_list)

    threading.Thread(target = read_server, args = (s,), daemon=True).start()


    var2 = StringVar()                                      # 聊天输入口
    var2.set('')                                    
    entryInput = Entry(window, width = 140, textvariable=var2)
    entryInput.place(x=5, y=305, width = 490, height = 95)


    # 发送按钮触发的函数,即发送信息
    def sendtext():
        line = var2.get()
        s.send(line.encode('utf-8'))
        var2.set('')                                        # 发送完毕清空聊天输入口

    #发送按钮
    sendButton = Button(window, text = '发 送', font=('Fangsong', 18), bg = 'white', command=sendtext)     
    sendButton.place(x=500, y=305, width = 150, height = 95)

    def on_closing():                                       # 窗口关闭二次确认函数,并确认后自动关闭程序
        if tkinter.messagebox.askokcancel("退出", "你确认要退出聊天室吗?"):
            window.destroy()
            sys.exit(0)

    window.protocol("WM_DELETE_WINDOW", on_closing)
    window.mainloop()
    

Login_gui_run()

Note: The server-side code needs to be run on the cloud server, and the client-side code needs to be run on our own computer! !

Then we need to open the corresponding port number

Here is an official tutorial of Alibaba Cloud https://developer.aliyun.com/article/791425 . Our project uses port 30000, so we only need to open this port. The final effect of opening is as follows:

 

After that, you just need to hang the server code on the cloud server and run it all the time.

The screenshot of the running effect of the cloud server is as follows:

Finally, you can also package the code of the client to generate an exe file, so that you can send this exe file to friends who live in other places to use! ! !

At this point, all work has come to an end! ! ! !

Guess you like

Origin blog.csdn.net/m0_56942491/article/details/124289328
Recommended