首页 » 运维教程 » 正文

Python socket C/S结构的聊天室应用实现?

眉心 2024-09-20 运维教程 42 views 0

扫一扫用手机浏览

文章目录 [+]

在网络编程中,C/S(Client/Server)结构是一种常见的架构模式,在这种模式下,客户端和服务器端通过一个通信协议进行交互,本文将详细介绍如何使用Python的socket库来实现一个简单的聊天室应用,该应用基于C/S结构,包括服务器端和客户端两部分。

二、Python socket库简介

Python的socket库提供了标准的BSD Sockets API,可以使用它来创建TCP/IP套接字,这些套接字可以用于TCP或UDP连接,socket库提供了一些基本的网络服务功能,如:创建套接字、绑定地址和端口、监听连接、接收和发送数据等。

三、服务器端实现

服务器端的主要任务是监听客户端的连接请求,接收客户端发送的消息,并将消息广播给所有在线的客户端,以下是服务器端的实现步骤:

1. 导入socket库,并创建一个socket对象。

2. 绑定服务器的IP地址和端口号。

3. 调用listen方法开始监听客户端的连接请求。

4. 使用一个无限循环来接受客户端的连接请求,当有新的客户端连接时,创建一个新的线程来处理这个客户端的所有请求。

5. 在每个线程中,接收客户端发送的消息,并将消息广播给所有在线的客户端。

6. 关闭与客户端的连接。

四、客户端实现

客户端的主要任务是连接到服务器,发送消息,并接收其他客户端发送的消息,以下是客户端的实现步骤:

2. 连接到服务器的IP地址和端口号。

3. 使用一个无限循环来发送和接收消息。

4. 当用户输入消息时,将消息发送给服务器。

5. 接收服务器广播的消息,并显示在屏幕上。

6. 关闭与服务器的连接。

五、代码实现

以下是服务器端和客户端的代码实现:

服务器端代码:

```python

import socket

import threading

# 创建socket对象

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定IP地址和端口号

server.bind(('localhost', 8080))

# 监听连接请求

server.listen(5)

clients = [] # 存储所有在线的客户端

nicknames = [] # 存储所有在线的客户端昵称

def broadcast(message):

"""广播消息"""

for client in clients:

client.send(message)

def handle(client):

"""处理客户端请求"""

while True:

try:

msg = client.recv(1024)

broadcast(msg)

except:

index = clients.index(client)

clients.remove(client)

client.close()

nickname = nicknames[index]

nicknames.remove(nickname)

broadcast(f'{nickname} left the chat!'.encode('ascii'))

break

while True:

client, address = server.accept()

print(f'Connected with {str(address)}')

clients.append(client)

nickname = input('Choose a nickname: ')

nicknames.append(nickname)

client.send('NICK ' + nickname.encode('ascii'))

thread = threading.Thread(target=handle, args=(client,))

thread.start()

```

客户端代码:

import sys

from termcolor import colored

from time import sleep

from getpass import getpass

sys.stdout.write(colored('Welcome to Chat Room!', 'green'))

sys.stdout.write('

')

sys.stdout.flush()

nickname = input('Choose a nickname: ')

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.connect(('localhost', 8080))

client.send('NICK ' + nickname.encode('ascii'))

def receive():

"""接收消息"""

msg = client.recv(1024).decode('ascii')

if msg == 'NICK':

nick = client.recv(1024).decode('ascii')

print(f'Nickname of the user is {nick}!')

elif msg == 'left the chat!':

print('Someone left the chat!')

sys.exit()

else:

print(msg)

print('An error occured!')

sys.exit()

def write(): """发送消息""" while True: msg = f'{nickname}: {input("")}' client.send(msg.encode('ascii')) if msg == 'bye': break receive() sleep(0.1) threading.Thread(target=write).start() client.close() # 启动接收和发送消息的线程 # 如果用户输入"bye",则退出程序 # 关闭与服务器的连接 # 主函数 def main(): print('Connecting...') sys.stdout.write(colored('Connecting...', 'green')) sys.stdout.write('

') sys.stdout.flush() nick = getpass('Enter your nickname: ') sys.stdout.write(colored('Connecting...', 'green')) sys.stdout.write('

') sys.stdout.flush() sys.stdout.write(colored('Connecting...', 'green')) sys.stdout.write('

') sys.stdout.flush() print('Connected!') sys.stdout.write(colored('Connected!', 'green')) sys.stdout.write('

') sys.stdout.flush() print('You are connected to the server!') sys.stdout.write(colored('You are connected to the server!', 'green')) sys.stdout.write('

') sys.stdout.flush() main() # 运行主函数 return main() if __name__ == '__main__': main() # 如果当前模块是主模块,则运行主函数;否则不执行任何操作。

# -*- coding: utf-8 -*- # Python program for implementation of chat room using socket library in python # Created on Sun Jan 19 13:57:59 2020 by guest # @guest # This program creates a simple chat room application based on Client-Server architecture using Python socket library and threads for handling multiple clients at the same time, where each client can send and receive messages from other clients connected to the server simultaneously over a network (LAN or Internet). The server listens for connection requests from clients, accepts them, and then creates a new thread for each client to handle their requests separately, allowing multiple clients to connect and communicate with each other simultaneously without any delay or lag in communication between them due to concurrency issues caused by handling multiple clients at once using threads instead of processes which would be more resource-intensive than necessary for this simple chat room application scenario involving only text-based messages being exchanged between clients over a network connection established through socket programming interface provided by Python standard library for network programming purposes such as file transfer protocol (FTP), email sending/receiving protocols like IMAP/POP3 etcetera...

相关推荐

登录服务器怎么登录不了账号了呢苹果

在当今信息化社会,网络已经成为了我们生活、工作、学习中不可或缺的一部分,而服务器作为网络的核心,承载着各种应用服务,为我们提供了便...

运维cms 2024-09-20 阅读39 评论0

Java中BIO、NIO、AIO的示例分析

在Java网络编程中,BIO、NIO和AIO是非常重要的概念,它们分别代表了Java网络编程的三种不同模式:阻塞I/O、非阻塞I/...

技术 2024-09-20 阅读45 评论0

云服务器操作

在当今的互联网时代,服务器已经成为了企业和个人必不可少的基础设施,而在众多的服务器技术中,Socket编程是一种非常重要的网络编程...

帮助 2024-09-20 阅读38 评论0

sls 6.2

Slax 6.1.0是一个基于Java语言的高性能网络通信框架,它提供了一种简单、高效的方式来实现网络通信,Slax 6.1.0采...

技术 2024-09-20 阅读34 评论0

常见的socket error错误有哪些

在计算机编程中,socket(套接字)是一种实现网络通信的技术,在使用socket时,我们可能会遇到各种错误,本文将介绍一些常见的...

世外 2024-09-20 阅读53 评论0