gpt4 book ai didi

python - 基于socket的简单python聊天程序

转载 作者:太空狗 更新时间:2023-10-29 21:53:16 24 4
gpt4 key购买 nike

我正在编写一个简单的基于套接字的聊天程序,允许服务器向客户端发送和接收消息。客户端可以向服务器发送消息,但是当我尝试从服务器发送消息时,它崩溃并提示"file"对象具有属性“recv”。

服务器.py

import socket
import os
import select
import sys

def prompt():
sys.stdout.write('<You> ')
sys.stdout.flush()

try:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print 'Failed to create socket'
sys.exit()

PORT = 9050
HOST = '127.0.0.1'
RECV_BUFFER = 4096

server_socket.bind((HOST, PORT))
server_socket.listen(10)

input = [server_socket, sys.stdin]

print 'Chat Program'
prompt()

while 1:

inputready, outputready, exceptready = select.select(input,[],[])

for sock in inputready:

if sock == server_socket:
client, address = server_socket.accept()
input.append(client)
#data = sock.recv(RECV_BUFFER)
#if data:
#sys.stdout.write(data)
else:
data = sock.recv(RECV_BUFFER)
if data:
sys.stdout.write(data)
else:
msg = sys.stdin.readline()
server_socket.send('\r<Server>: ' + msg)
prompt()



server_socket.close()

客户端.py

import socket
import os
import select
import sys

def prompt():
sys.stdout.write('<You> ')
sys.stdout.flush()

HOST = '127.0.0.1'
PORT = 9050
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()

s.connect((HOST, PORT))

print 'Connected to remote host. Start sending messages'
prompt()

while 1:

socket_list = [sys.stdin, s]

read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])

for sock in read_sockets:
if sock == s:
data = sock.recv(4096)
if not data:
print '\nDisconnected from chat server'
sys.exit()
else:
sys.stdout.write(data)
prompt()
else:
msg = sys.stdin.readline()
s.send('\r<Client>: ' + msg)
prompt()

最佳答案

好吧,在你的服务器中你正在做(缩写)

input = [server_socket, sys.stdin]
inputready, outputready, exceptready = select.select(input,[],[])
for sock in inputready:
if sock == server_socket:
...
else:
data = sock.recv(RECV_BUFFER)

所以当 sys.stdin 上有东西进来时,它不是 server_socket 所以它会转到 else 并尝试 recv ,但它不是套接字。 stdin 应该使用 read 而不是 recv。像下面这样的结构对我来说最有意义。

if sock == server_socket:
...
elif sock == sys.stdin:
data = sock.readline()
for s in input:
if s not in (server_socket, sys.stdin):
s.send(data)
else:
...

关于python - 基于socket的简单python聊天程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16530563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com