用python编写一个可以互相通信的客户端和服务端,可以显示身份
时间: 2024-03-18 07:41:10 浏览: 70
好的,我可以帮您解答这个问题。下面是一个简单的Python客户端和服务端代码,可以通过socket进行通信,同时在通信时可以显示身份。
服务端代码:
```python
import socket
# 创建一个socket对象
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = socket.gethostname()
# 设置端口号
port = 9999
# 绑定端口号
serversocket.bind((host, port))
# 设置最大连接数,超过后排队
serversocket.listen(5)
while True:
# 建立客户端连接
clientsocket, addr = serversocket.accept()
print("连接地址: %s" % str(addr))
# 发送欢迎消息到客户端
message = '欢迎来到服务器!' + "\r\n"
clientsocket.send(message.encode('utf-8'))
while True:
# 接收客户端消息
data = clientsocket.recv(1024).decode('utf-8')
if not data:
break
print("来自客户端的消息:%s" % data)
# 发送消息到客户端
message = '已确认收到消息:' + data + "\r\n"
clientsocket.send(message.encode('utf-8'))
# 关闭连接
clientsocket.close()
```
客户端代码:
```python
import socket
# 创建一个socket对象
clientsocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = socket.gethostname()
# 设置端口号
port = 9999
# 连接服务,指定主机和端口
clientsocket.connect((host, port))
# 接收欢迎消息
message = clientsocket.recv(1024).decode('utf-8')
print(message)
while True:
# 发送消息到服务端
message = input("请输入您要发送的消息:")
clientsocket.send(message.encode('utf-8'))
# 接收服务端回复
data = clientsocket.recv(1024).decode('utf-8')
print("来自服务端的回复:%s" % data)
# 关闭连接
clientsocket.close()
```
在运行上述代码时,您需要先启动服务器,然后再运行客户端。在客户端输入消息后,服务器会将消息原样返回给客户端,并在服务器端显示客户端的IP地址和端口号。在客户端收到服务端的回复后,会显示服务端的IP地址和端口号。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)