我正在尝试创建一个简单的聊天服务器。我已经能够使用“ 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
答案 0 :(得分:1)
您忘记了使用print()
来显示服务器中的数据
while True:
print( n.send("sending stuff") )
顺便说一句:在服务器中,您两次发送相同的数据-使用conn.send()
和conn.sendall()