Use socket and threading to create a multi-threaded chat today
ready:
- One computer with virtual machine (VMware) installed (or two computers ( ̄︶ ̄)↗)
- Both the host and the virtual machine have python installed, and both have IDEs
My configuration:
- win10 host, Ubuntu virtual machine
- 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
on windows
import socket
import threading
def recv(udp_socket):
while True:
msg=udp_socket.recv(1024)
print(msg.decode('utf-8'))
def send(udp_socket,addr):
while True:
msg=input("输入:")
udp_socket.sendto(msg.encode('utf-8'),addr)
def main():
# 1. 创建套接字
udp_socket=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 2. 绑定ip和port
udp_socket.bind(('192.168.1.2',7892))
# 3.对方的ip和port
addr=('192.168.48.142',7893)
# 4. 创建线程
t_send=threading.Thread(target=send,args=(udp_socket,addr))
t_recv=threading.Thread(target=recv,args=(udp_socket,))
t_send.start()
t_recv.start()
if __name__=='__main__':
main()
On the virtual machine
import socket
import threading
def recv(udp_socket):
while True:
msg=udp_socket.recv(1024)
print(msg.decode('utf-8'))
def send(udp_socket,addr):
while True:
msg=input("输入:")
udp_socket.sendto(msg.encode('utf-8'),addr)
def main():
# 1. 创建套接字
udp_socket=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 2. 绑定ip和port
udp_socket.bind(('192.168.48.142',7893))
# 3.对方的ip和port
addr=('192.168.1.2',7892)
# 4. 创建线程
t_send=threading.Thread(target=send,args=(udp_socket,addr))
t_recv=threading.Thread(target=recv,args=(udp_socket,))
t_send.start()
t_recv.start()
if __name__=='__main__':
main()
Of course, the same computer can also communicate with each other (same ip), as long as the ports are different.