Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send a server response to the client? (Python sockets)

I made a client and server code with the socket module in python 2.7. The problem is I don't know/not able to send a server response. This is my client code:

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

Server

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

When the server does:

sock.sendto("ktov")

I get this error:

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

I'm new to network programming so I have no clue what's the problem, how do you really send a response to the server?

like image 906
user3012765 Avatar asked Mar 20 '23 23:03

user3012765


1 Answers

client, addr = sock.accept()

please note that client is the new socket object that you should be using

data = client.recv(4096)

Here you use client

sock.send("ktov")

Here you use sock, which is a listening socket, not the socket connection to your client. You should instead use:

client.sendall(data)
like image 53
pfc Avatar answered Apr 26 '23 12:04

pfc