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

我用python 2.7中的socket模块编写了一个客户机和服务器代码。问题是我不知道/无法发送服务器响应。

这是我的客户代码: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

我是网络编程新手,所以我不知道是什么问题,你真的如何向服务器发送响应?

你可能感兴趣的:(服务器响应客户端socket)