python - 如何使用 conn.send() 向客户端发送数据

标签 python python-3.x sockets

我正在尝试创建一个简单的聊天服务器。我已经能够使用“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/

相关文章:

python - 如何配置 pycharm/intellij idea 来运行 tox 测试

python - pyqt5子级使用qml文件访问

python - bash 在错误的地方寻找 python 可执行文件

python-3.x - flask 测试 : preprocess_request(), dispatch_request()

Java 套接字 : can you send from one thread and receive on another?

python - scrapy-playwright :- Downloader/handlers: scrapy. exceptions.NotSupported: AsyncioSelectorReactor

python - 将 2D 列表分配给 2 个 Dataframe 列 Pandas

python-3.x - 如何从没有扩展名python的路径中获取特定文件名

javascript - NodeJS 到客户端 : large data sending performance

c - FreeBSD 或 NetBSD 的 C 套接字编程最快的 I/O 策略或方法是什么?