gpt4 book ai didi

python - 如何向客户端发送服务器响应? (Python 套接字)

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:41 24 4
gpt4 key购买 nike

我用 python 2.7 中的套接字模块编写了客户端和服务器代码。问题是我不知道/无法发送服务器响应。这是我的客户端代码:

import socket
from optparse import OptionParser

def main():
sock = None
parser = OptionParser()
parser.add_option("-z", action="store", dest="data")
options, args = parser.parse_args()
try:
print "Creating socket"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print "Connecting to localhost on port 9900"
sock.connect(('127.0.0.1', 9900))
print "Connection success!"
except socket.error, msg:
print "Failed to create and connect. Error code: " + str(msg[0]) + " , Error message : " + msg[1]
exit()

if options.data:
print "Data parameter received."
data = options.data
else:
data = raw_input("Enter data to send to server: ")
print 'Attempting to send data over the socket...'
sock.sendall(data)
print 'Data sent to server! Now waiting for response...'
while 1:
data = sock.recv(4096)
print "Received response:" + str(data)

sock.close()
del sock

服务器

from socket import *

print 'Attempting to start server on port 9900..'
sock = socket(AF_INET, SOCK_STREAM)
sock.bind(('', 9900))
sock.listen(SOMAXCONN)

print 'Server is now listening on port 9900!'
client, addr = sock.accept()
print client
print 'Waiting for data...'
data = client.recv(4096)
print 'Received data from client: ' + str(data)
print "ok"
sock.send("ktov")
print "Sent the same data back to the client!"

sock.close()
del sock

当服务器执行时:

sock.sendto("ktov")

我收到这个错误:

socket.error: [Errno 10057] A request to send or receive data was disallowed bec ause the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

我是网络编程的新手,所以我不知道问题出在哪里,您如何真正向服务器发送响应?

最佳答案

client, addr = sock.accept()

请注意,client 是您应该使用的新套接字对象

data = client.recv(4096)

这里使用客户端

sock.send("ktov")

这里使用的是 sock,它是一个监听套接字,而不是与客户端的套接字连接。您应该改用:

client.sendall(data)

关于python - 如何向客户端发送服务器响应? (Python 套接字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141954/

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