python socket编程,要求是p2p通信方式,有用户聊天界面,聊天界面有IP地址和端口号显示且可以输入目的IP地址和端口号与其P2P连接聊天
时间: 2024-04-10 21:34:41 浏览: 30
可以使用Python的socket库来实现P2P通信方式的用户聊天界面。以下是一个简单的示例代码:
```python
import socket
import threading
def receive_message(sock):
while True:
try:
data, addr = sock.recvfrom(1024)
print(f"From {addr[0]}:{addr[1]}: {data.decode()}")
except OSError:
break
def send_message(sock, dest_ip, dest_port):
while True:
message = input()
sock.sendto(message.encode(), (dest_ip, dest_port))
# 获取本地IP地址
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(("8.8.8.8", 80))
local_ip = sock.getsockname()[0]
sock.close()
# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定本地IP地址和端口号
local_port = 12345
sock.bind((local_ip, local_port))
# 启动接收消息线程
receive_thread = threading.Thread(target=receive_message, args=(sock,))
receive_thread.start()
# 输入目标IP地址和端口号
dest_ip = input("Enter destination IP address: ")
dest_port = int(input("Enter destination port number: "))
# 启动发送消息线程
send_thread = threading.Thread(target=send_message, args=(sock, dest_ip, dest_port))
send_thread.start()
# 等待发送线程结束(可以使用Ctrl+C退出)
send_thread.join()
# 关闭套接字
sock.close()
```
这个示例代码创建了一个UDP套接字,并绑定了本地IP地址和端口号。它包括两个线程:接收消息线程和发送消息线程。接收消息线程通过recvfrom()方法接收其他用户发送的消息,并将其打印出来。发送消息线程通过input()函数获取用户输入的消息,并使用sendto()方法将消息发送给目标IP地址和端口号。
请注意,此示例代码仅实现了最基本的功能,没有处理连接异常、错误处理等。在实际应用中,还需要考虑更多的错误处理和安全性问题。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)