socket实现两人聊天
时间: 2023-11-30 09:05:19 浏览: 19
要使用socket实现两人聊天,需要先创建一个服务器和一个客户端。服务器会监听来自客户端的连接请求,并将消息转发给所有已连接的客户端。客户端需要连接到服务器,并可以发送和接收消息。
下面是一个简单的示例代码:
服务器端代码(Python):
```python
import socket
# 创建TCP/IP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server_address = ('localhost', 8888)
print(f"starting up on {server_address[0]} port {server_address[1]}")
server_socket.bind(server_address)
# 监听连接请求
server_socket.listen(1)
while True:
# 等待客户端连接
print("waiting for a connection...")
client_socket, client_address = server_socket.accept()
print(f"connection from {client_address}")
while True:
# 接收来自客户端的消息
data = client_socket.recv(1024)
if not data:
break
# 将消息转发给所有已连接的客户端
print(f"received {data.decode('utf-8')} from {client_address}")
for sock in [s for s in client_sockets if s != client_socket]:
sock.sendall(data)
# 关闭客户端连接
print(f"closing connection from {client_address}")
client_socket.close()
```
客户端代码(Python):
```python
import socket
import threading
def receive_messages(client_socket):
while True:
# 接收来自服务器的消息
data = client_socket.recv(1024)
if not data:
break
# 显示接收到的消息
print(f"received {data.decode('utf-8')}")
# 创建TCP/IP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('localhost', 8888)
print(f"connecting to {server_address[0]} port {server_address[1]}")
client_socket.connect(server_address)
# 启动接收消息的线程
threading.Thread(target=receive_messages, args=(client_socket,), daemon=True).start()
while True:
# 发送消息到服务器
message = input(">> ")
client_socket.sendall(message.encode('utf-8'))
# 关闭客户端连接
client_socket.close()
```
在运行服务器和客户端之前,请确保已安装Python和socket模块,并将代码保存在不同的文件中。运行服务器代码后,可以启动一个或多个客户端,每个客户端都可以与服务器通信。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)