4
#!/usr/bin/env python import socket clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(('192.168.1.123', 5162)) clientsocket.send('getval.1') clientsocket.close clientsocket.bind(('192.168.1.124', 5163)) clientsocket.listen(1) while True: connection, address=clientsocket.accept() value=connection.recv(1024) print value 

I'm trying to get python to send a message to the server, and in return the server responds. Yet when I execute this code it gives me

Socket.error: [Errno 10022] An invalid argument was supplied 
2
  • always show full error message (traceback). There are more usefull inforamtion. Which line makes problem ? Commented Nov 6, 2016 at 4:34
  • first you need () in close() to close it. Second: you can't use closed socket again - you have to create new socket. BTW: you could use the same connection to send() data to server and to recv() data from server - if you only change server too. Commented Nov 6, 2016 at 4:49

1 Answer 1

5

It seems you wrote a mixed code of server and client Here a simple sample of codes for socket programming the first on server side and the second on client

Server side code:

# server.py import socket import time # create a socket object serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.gethostname() port = 9999 # bind to the port serversocket.bind((host, port)) # queue up to 5 requests serversocket.listen(5) while True: # establish a connection clientsocket,addr = serversocket.accept() print("Got a connection from %s" % str(addr)) currentTime = time.ctime(time.time()) + "\r\n" clientsocket.send(currentTime.encode('ascii')) clientsocket.close() 

and now the client

# client.py import socket # create a socket object s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.gethostname() port = 9999 # connection to hostname on the port. s.connect((host, port)) # Receive no more than 1024 bytes tm = s.recv(1024) s.close() print("The time got from the server is %s" % tm.decode('ascii')) 

The server simply remained listened for any client and when it finds out a new connection it returns current datetime and closes the client connection

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.