我需要客户端向服务器端写入



我正在努力让客户端能够向服务器发送消息,现在客户端只能相互发送消息,我添加了datafromclient的行,但它只接收客户端的第一个输入,之后只有客户端交换消息。

这是我的server.py 代码

import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),1234))
s.listen()
print("Waiting for connections")
clients = []
unames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
uname = unames[index]
broadcast(f"{uname} left the server!".encode("utf-8"))
unames.remove(uname)
break
def receive():
while True:
client, addr = s.accept()
print(f"Connected with {str(addr)}")
client.send('uname'.encode("utf-8"))
uname = client.recv(1024).decode("utf-8")
unames.append(uname)
clients.append(client)
broadcast(f"{uname} joined the server!".encode("utf-8"))
client.send("nWelcome to the server!".encode("utf-8"))
fOpen = open("rules.txt", "r")
client.send(fOpen.read().encode("utf-8"))
datafromclient = client.recv(1024)
print(datafromclient.decode("utf-8"))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
s.close()

这是客户.py

import socket
import threading
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect((socket.gethostname(),1234))
uname = input("Username: ")
def receive():
while True:
try:
message = c.recv(1024).decode("utf-8")
if message == "uname":
c.send(uname.encode("utf-8"))
else:
print(message)
except:
print("An error occurred!")
c.close()
break
def write():
while True:
message = f'{uname}: {input("")}'
c.sendall(message.encode("utf-8"))
recv_thread = threading.Thread(target=receive)
recv_thread.start()
write_thread = threading.Thread(target=write)
write_thread.start()

这应该会给你一个想法:

server.py:

import socket
import threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((socket.gethostbyname(socket.gethostname()), 1234))
clients = []
def handle_client(conn, addr):
clients.append(conn)
while True:
msg_length = conn.recv(64).decode("utf-8")
if msg_length:
msg = conn.recv(int(msg_length)).decode("utf-8")
print(msg)
if msg == "!DISCONNECT":
break
for client in clients:
client.send(msg.encode("utf-8")) 
clients.remove(conn)
conn.send('Bye'.encode("utf-8")) 
conn.close()
server.listen()
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()

client.py:

import socket
import threading
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((socket.gethostbyname(socket.gethostname()), 1234))
def send():
msg = input(">>> ")
client.send(str(len(msg)).encode("utf-8").ljust(64))
client.send(msg.encode("utf-8"))
thread = threading.Thread(target=send)
thread.start()
while True:
if client.recv(2048).decode("utf-8") == "Bye":
break
thread = threading.Thread(target=send)
thread.start()

相关内容

  • 没有找到相关文章

最新更新