Use socket in python to make a simple chat tool

socket is a package that comes with python, no additional installation is required

ready:

  1. One computer with virtual machine (VMware) installed (or two computers ( ̄︶ ̄)↗)
  2. Both the host and the virtual machine have python installed, and both have IDEs

My configuration:

  1. win10 host, Ubuntu virtual machine
  2. IDE is pycharm

Before creating a chat tool, we need to know the ip of the host and virtual machine.
For Ubuntu, right-click to open the terminal and enter the command to view the ip

ifconfig

For win, win+cmd open the terminal, enter the command to view ip

ipconfig

My win host ip and virtual machine ip are respectively

192.168.1.2 # win
192.168.48.142 # Ubuntu

We can configure it if we know the ip

On win, the code is as follows

import socket
def main():
    local_addr = ('192.168.1.2', 8080) # win主机ip和端口号(端口号自定,不和其他软件冲突就好)
    dest_addr = ('192.168.48.142', 8877) # Ubuntu虚拟机ip和端口号 
    while True:
        # 创建udp套接字
        socket_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # 绑定win主机ip
        socket_udp.bind(local_addr)
        # 接受虚拟机传来的文件,1024为最大字节数
        data_to_receive = socket_udp.recvfrom(1024)
        # 将接收到的信息打印出来
        print(data_to_receive[0].decode('utf-8'))
        # 输入发送的内容
        data_to_send = input("please enter:")
        socket_udp_send.sendto(data_to_send.encode('utf-8'), dest_addr)
        # 关闭套接字
        socket_udp_send.close()
if __name__ == '__main__':
    main()


On Ubuntu, the code is as follows (almost the same as above)

import socket
def main():
    local_addr = ('192.168.48.142', 8877)
    dest_addr = ('192.168.1.2', 8080)
    while True:
        socket_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        socket_udp.bind(local_addr)
        data_to_send = input("please enter:")
        socket_udp.sendto(data_to_send.encode('utf-8'), dest_addr)
        data_to_receive = socket_udp.recvfrom(1024)
        print(data_to_receive[0].decode('utf-8'))
        socket_udp.close()
if __name__ == '__main__':
    main()

The chat effect is as follows.
Since the win code is first received and then sent, Ubuntu is first sent and then received, so enter it in Ubuntu first. This code is a half-duplex chat mode with one person and one sentence
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41459262/article/details/106798801