服务器端
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : homework.py
# @Author : YeHao
# @Contact : onehour60mins@163.com
# @Date : 2018/8/8 17:28
# @Desc :
"""
写一个服务器,可以和多个客户端同时通信,并且把接收到的消息显示在屏幕上
"""
import socket
from random import randint
from threading import Thread
import pygame
"""
1. 想要结束一个进程就是让它里面的所有进程都借宿,进程才会结束
2. 想要关闭一个子线程,就是想方设法让子线程中的任务结束(就是让run()结束)
3. 如果一个线程崩溃(发生异常),不会影响其他线程
"""
WIDTH = 600
HEIGHT = 600
IP = '10.7.181.90'
PORT = 12345
class Color:
white = 255, 255, 255
@staticmethod
def rand_color():
return randint(0, 255), randint(0, 255), randint(0, 255)
class Message:
"""文字信息"""
def __init__(self, text):
self.text = text
self.x = 600
self.y = randint(0, 300)
self.color = Color.rand_color()
self.speed = randint(2, 5)
self.is_alive = True
def move(self):
self.x -= self.speed
# 越界判断
if self.x < - 50:
self.is_alive = False
class AcceptThread(Thread):
"""接收请求的线程"""
def __init__(self, server: socket.socket):
super().__init__()
self.server = server
def run(self):
while True:
conversation, address = self.server.accept()
print('接收到客户端的请求')
# 来了一个客户端请求,就给他创建一个子线程,来处理对应消息
conversation_thread = ConversationThread(conversation)
conversation_thread.start()
class ConversationThread(Thread):
"""处理不同的客户端信息"""
all_messages = [] # 保存所有的消息
def __init__(self, conversation: socket.socket):
super().__init__()
self.conversation = conversation
# 让服务器和客户端一直保持通话
def run(self):
while True:
try:
# 接收客户端发来的消息
re_msg = self.conversation.recv(1024).decode()
# 接收到消息就创建一个消息对象
message = Message(re_msg)
# 保存所有的消息
ConversationThread.all_messages.append(message)
# 给客户端发送消息
self.conversation.send(' '.encode())
except ConnectionResetError:
print('[XXX已下线]')
break
def create_server():
server = socket.socket()
server.bind((IP, PORT))
server.listen(512)
# 在子线程去监听客户端的请求
server_thread = AcceptThread(server)
server_thread.start()
if __name__ == '__main__':
# 准备显示信息的屏幕
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
screen.fill((254, 223, 225))
pygame.display.flip()
create_server()
# 让屏幕可以一直存在
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
# 获取每条信息显示在屏幕上
screen.fill((254, 223, 225))
for message in ConversationThread.all_messages:
if message.is_alive:
# 显示信息
font = pygame.font.SysFont('Times', 30)
text = font.render(message.text, True, message.color)
screen.blit(text, (message.x, message.y))
# 移动
message.move()
else:
ConversationThread.all_messages.remove(message)
pygame.display.update()
客户端
import socket
IP = '10.7.181.90'
PORT = 12345
if __name__ == '__main__':
client = socket.socket()
client.connect((IP, PORT))
while True:
msg = input('>>>')
client.send(msg.encode())
print(client.recv(1024).decode())