gpt4 book ai didi

Python,如何通过 TCP 发送数据

转载 作者:可可西里 更新时间:2023-11-01 02:31:48 29 4
gpt4 key购买 nike

我需要创建一个简单的服务器来监听 TCP 连接。如果它收到文本 on<EOF>off<EOF>然后它发回(回显)success .接收部分正在工作,但现在我需要它发回 success .

代码:

# import threading
import SocketServer

class TCPHandler(SocketServer.BaseRequestHandler):

def handle(self):
self.msg = self.request.recv(1024).strip()
if self.msg == "on<EOF>":
print "Turning On..."
#ECHO "SUCCESS<EOF>" <----- I need the server to echo back "success"
if self.msg == "off<EOF>":
print "Turning Off..."
#ECHO "SUCCESS<EOF>" <----- I need the server to echo back "success"


if __name__ == "__main__":
host, port = '192.168.1.100', 1100

# Create server, bind to local host and port
server = SocketServer.TCPServer((host,port),TCPHandler)

print "server is starting on ", host, port

# start server
server.serve_forever()

最佳答案

好吧,我是在遵循一个非常好的教程前一天完成的,找不到链接,但这是代码

客户端.py

import socket

host = socket.gethostname()
port = 12345 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))

对于服务器

echo_server.py

import socket

host = '' # Symbolic name meaning all available interfaces
port = 12345 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))

print host , port
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:

try:
data = conn.recv(1024)

if not data: break

print "Client Says: "+data
conn.sendall("Server Says:hi")

except socket.error:
print "Error Occured."
break

conn.close()

关于Python,如何通过 TCP 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34653875/

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