我正在尝试创建一个简单的聊天服务器。我已经能够使用“client.send()”通过客户端向服务器发送信息,但我似乎无法执行相同的服务器->客户端
我尝试过使用 conn.send() 和 conn.sendall() 等方法,但是(我猜因为代码是在尝试中)它们似乎在初始 conn.send(str.encode( “已连接”))
服务器代码
import socket
from _thread import *
import sys
server = "192.168.0.4"
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(2)
print("Waiting for a connection, Server Started")
def threaded_client(conn):
conn.send(str.encode("Connected"))
reply = ""
while True:
conn.send(str.encode(str(reply)))
try:
data = conn.recv(2048*1)
reply = data.decode("utf-8")
if not data:
print("Disconnected")
break
else:
print("Received: ", reply)
print("Sending : ", reply)
conn.sendall(str.encode(reply)) #Where I want to send information to the client
except:
break
print("Lost connection")
conn.close()
while True:
conn, addr = s.accept()
print("Connected to:", addr)
start_new_thread(threaded_client, (conn,))
客户端代码
import socket
class Network:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "192.168.0.4"
self.port = 5555
self.addr = (self.server, self.port)
self.id = self.connect()
print(self.id)
def connect(self):
try:
self.client.connect(self.addr)
return self.client.recv(2048).decode()
except:
pass
def send(self, data):
try:
self.client.send(str.encode(data))
return self.client.recv(2048).decode()
except socket.error as e:
print(e)
from network import Network
n = Network()
while True:
n.send("sending stuff") #this works/sends properly
最佳答案
您忘记使用print()
来显示来自服务器的数据
while True:
print( n.send("sending stuff") )
顺便说一句:在服务器中,您发送相同的数据两次 - 使用 conn.send()
和 conn.sendall()
关于python - 如何使用 conn.send() 向客户端发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55564890/