Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Server Client WinError 10057

I'm making a server and client in Python 3.3 using the socket module. My server code is working fine, but this client code is returning an error. Here's the code:

import socket
import sys
import os

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('192.168.1.5', 4242)
sock.bind(server_address)

while True:
    command = sock.recv(1024)
    try:
        os.system(command)
        sock.send("yes")
    except:
        sock.send("no")

And here's the error:

Error in line: command = sock.recv(1024)
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected  and (when sending on a datagram socket using a sendto call) no address was supplied

What on earth is going on?

like image 244
user3677994 Avatar asked May 27 '14 02:05

user3677994


2 Answers

It looks like you're confused about when you actually connect to the server, so just remember that you always bind to a local port first. Therefore, this line:

server_address = ('192.168.1.5', 4242)

Should actually read:

server_address = ('', 4242)

Then, before your infinite loop, put in the following line of code:

sock.connect(('192.168.1.5', 4242))

And you should be good to go. Good luck!

EDIT: I suppose I should be more careful with the term "always." In this case, you want to bind to a local socket first.

like image 195
KnightOfNi Avatar answered Nov 01 '22 02:11

KnightOfNi


You didn't accept any requests, and you can only recv and/or send on the accepted socket in order to communicate with client.

Does your server only need one client to be connected? If so, try this solution:

Try adding the following before the while loop

sock.listen(1)         # 1 Pending connections at most
client=sock.accept()   # Accept a connection request

In the while loop, you need to change all sock to client because server socket cannot be either written or read (all it does is listening at 192.168.1.5:4242).

like image 1
Travor Liu Avatar answered Nov 01 '22 03:11

Travor Liu