请模拟socket两个客户端,一个服务端的聊天示例代码
时间: 2023-08-21 11:02:42 浏览: 50
以下是一个简单的Socket聊天程序的示例代码,其中包括一个服务端和两个客户端:
服务端代码:
```python
import socket
import threading
def handle_client(client_socket, addr):
while True:
data = client_socket.recv(1024)
if not data:
break
print("[{}] {}".format(addr, data.decode()))
client_socket.sendall("[Echo]: {}".format(data.decode()).encode())
print("[{}] disconnected".format(addr))
client_socket.close()
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("localhost", 8888))
server_socket.listen(5)
print("[Server] Listening on port 8888...")
while True:
client_socket, addr = server_socket.accept()
print("[Server] New client connected: {}".format(addr))
client_thread = threading.Thread(target=handle_client, args=(client_socket, addr))
client_thread.start()
if __name__ == '__main__':
start_server()
```
客户端1代码:
```python
import socket
def start_client():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 8888))
while True:
message = input("[You]: ")
if message == "exit":
break
client_socket.sendall(message.encode())
data = client_socket.recv(1024)
print("[Server]: {}".format(data.decode()))
print("[Client] Disconnected")
client_socket.close()
if __name__ == '__main__':
start_client()
```
客户端2代码:
```python
import socket
def start_client():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 8888))
while True:
message = input("[You]: ")
if message == "exit":
break
client_socket.sendall(message.encode())
data = client_socket.recv(1024)
print("[Server]: {}".format(data.decode()))
print("[Client] Disconnected")
client_socket.close()
if __name__ == '__main__':
start_client()
```
运行以上代码,打开两个客户端并连接到服务端,即可模拟Socket聊天程序的基本功能。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)