im trying to create a program that can do Command Line commands on my other pc over an TCP python server... but when i want to get the result of my command its just stuck there does nothing and staring at me... help will be appreciated
Client:
try:
sock.sendall("3")
if sock.recv(10000) == "ready for sandbox":
print "ready to transmit"
except:
print "error"
sys.exit(1)
while True:
try:
command = raw_input("--> ")
sock.sendall(command)
sock.recv(10000)
except:
print "connection lost"
sys.exit(1)
Server:
while True:
data = connection.recv(10000)
print >>sys.stderr, 'received "%s"' % data
elif data == "3":
connection.sendall("ready for sandbox")
while True:
try:
cmd_data = connection.recv(10000)
os.system(cmd_data +" > C:\output.txt")
result = open(r"C:\output.txt",'r').readlines()
connection.sendall(result)
except:
pass
I want to be able as the client always send commands and receive their outputs... and the Server should be error free as possible or atleast not to crash
By the way.. the indentations in my programs are ok if you find indentation mistakes it's probably because of stackoverflow...
Server cmd:
starting up on localhost port 10000
waiting for connection
connection from ('127.0.0.1', 52674)
received "3"
Client cmd:
--> 3
connecting to localhost port 10000
ready to transmit
--> dir
Help? :(
The problem was that it tried to send loop instead of string so fixing the loop and str(result) did the job pretty much.... works flawlessly now
Related
I have made two scripts to practice using sockets in Python but I have trouble communicating after the connexion is established:
My scripts below :
Server.py
#!/usr/local/bin/python3.5
import socket, sys
HOST = 'myIP'
PORT = 50000
counter = 0
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mySocket.bind((HOST,PORT))
except socket.error:
print("Socket connection failed.")
sys.exit
while 1:
print("Server ready, waiting for request...")
mySocket.listen(2)
connexion, adress = mySocket.accept()
counter+=1
print("Client connected, adress IP %s, port %s" % (adress[0], adress[1]))
msgServeur="Connected to server PytPyt. You can send messages."
connexion.send(msgServeur.encode("Utf8"))
msgClient = connexion.recv(1024).decode("Utf8")
while 1:
print("C>", msgClient)
if msgClient.upper() == "END" or msgClient == "":
break
msgServeur = input("S> ")
connexion.send(msgServeur.encode("Utf8"))
msgClient = connexion.recv(1024).decode("Utf8")
connexion.send("end".encode("Utf8"))
print("Connexion finished.")
connexion.close()
ch=input("<R>etry <T>erminate?")
if ch.upper() =='T':
break
Client.py
#!/usr/local/bin/python3.5
import socket, sys
HOST = 'myIP'
PORT = 50000
mySocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mySocket.connect((HOST, PORT))
except socket.error:
print("Connexion failed.")
sys.exit()
print("Connexion established with server.")
msgServeur = mySocket.recv(1024).decode("Utf8")
while 1:
if msgServeur.upper == "END" or msgServeur == "":
break
print("S>", msgServeur)
msgClient=input("C> ")
mySocket.send(msgClient.encode("Utf8"))
msgServeur = mySocket.recv(1024).decode("Utf8")
print("Connexion terminated.")
mySocket.close()
When I execute the two scripts I have the result below :
Server :
myPrompt : ./Server.py &
Server ready, waiting for request...
Client connected, adresse IP myIP, port 53551
Client :
myPrompt : ./Client.py &
Connexion established with server.
S> Connected to server PytPyt. You can send messages.
C> hello
-bash: hello: command not found
[1]+ Stopped ./Client.py
It seems that my message is executed as a bash command and not a message to send. However if I run the job again it will work :
Client :
myPrompt : %
./Client.py
hello
Server :
C> hello
S>
But it fails again right after. I have to run the job again any time I want to send a message.
Do you know where the mistake is?
Actually problem lay in script launching. You using following command
./Client.py &
With & the process starts in the background, so you can continue to use the shell. & detach stdin of your script from terminal. And all that you print in terminal after script launching will be interpreted as bash commands.
Try to use just
./Client.py
I'm currently working on a project for a class. It consists in code a simple chat client (protocol given by the teacher) to do (at first) some simple tasks.
My problem is that after I send a mensage on the globlal channel or in other channel that doesn't require the use of a command, and try to send any command, the server replies with an error, saying something like: "msgbeforemsgbeforeCOMMAND" is not a valid command. I just cannot figure it out why this is happening...
(another thing, note that my dictionary is not printing the right why, I dont know why to)
ex:
chat running
import socket, select, string, sys
import threading
import time
def prompt():
sys.stdout.write('<You>: ')
sys.stdout.flush()
tLock = threading.Lock()
shutdown = False
def receber(sock):
while not shutdown:
try:
tLock.acquire()
while True:
data = sock.recv(1024)
if not data:
print ('Disconnected from server\n')
sys.exit()
else:
print ('<server>: %s' % (data.decode()))
sys.stdout.write(data)
except:
pass
finally:
tLock.release()
#Main Function
if __name__ == "__main__":
host = 'mini.alunos.di.uevora.pt'
port = 143
#IP do servidor
try:
busca_ip = socket.gethostbyname( host )
print ('Chat server IP: %s Port: %d \nNow connecting...\n' %(busca_ip, port))
except socket.gaierror:
#Não conseguiu o IP do servidor
print ('Hostname could not be resolved. Exiting.')
sys.exit()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
# connectar ao host
try :
s.connect((busca_ip, port))
s.setblocking(0)
except :
print ('Unable to connect to the server.')
sys.exit()
print ('Connected to chat server. You may start chatting\n')
COM_ARG = {'_Comando_': '_Argumentos_',
'NICK': '<nickname> [\<password>]',
'MSG': '<recipient> \<message>',
'ENTER': '<room>',
'LEAVE': '<room> [\<message>]',
'RLIST':'',
'ULIST':''}
for chave, valor, in COM_ARG.items():
print (("%s %s") % (chave,valor))
print ('\n')
comandos = COM_ARG.keys()
#criar thread para o socket
t = threading.Thread(target = receber, args=(s,))
t.start()
while True:
msg = input('<You>: ')
msg = msg.strip()
msg12 = msg.upper()
msg12 = msg12.split()
try:
if msg12[0] in comandos:
msg = msg + '\n'
except:
pass
s.send(msg.encode())
time.sleep(0.25)
btw, sys.stdout.write(data) is doing something there?
Hope you could help me out.
(another thing, note that my dictionary is not printing the right why, I dont know why to)
Dictionary doesn't respect order.
My problem is that after I send a mensage on the globlal channel or in other channel that doesn't require the use of a command, and try to send any command, the server replies with an error, saying something like: "msgbeforemsgbeforeCOMMAND" is not a valid command. I just cannot figure it out why this is happening...
It's not just a problem with the code, the server recives the msgs, and keeps them until a '\n' appears, just then interprets the command. It's a "problem" with the protocol, but the code must be changed.
btw, sys.stdout.write(data) is doing something there?
Supposedly does the samething that print (data.decode()) does, but doesn't work in my case. I'm not sure.
I've checked few similar threads on stackoverflow.com and I think I might need to open non-blocking socket for my server script. Since, I'm not sure that this is the solution question title might be wrong. Let me explain what is my problem.
Server app waits for connection and once client connects it will ask for server ID, after that client will ask for server configuration and than client will send command to server to start measurement transmission. Here's simplified version of my code:
def conn_handler(self, connection, address):
self.logger.info("[%d] - Connection from %s:%d", 10, address[0], address[1])
sending_measurements_enabled = False
try:
while True:
data = connection.recv(2048)
if data:
command = get_command_from_data(data)
else:
command = None
if command == 'start':
sending_measurements_enabled = True
elif command == 'stop':
break
elif command == 'id':
connection.sendall(self.id)
elif command == 'cfg':
connection.sendall(self.cfg)
if sending_measurements_enabled:
connection.sendall(measurement)
except Exception as e:
print(e)
finally:
connection.close()
print("Connection closed")
And here is client script:
try:
sock.sendall(get_id_command)
data = sock.recv(2048) # Do I need to wait for response?
print(data)
sock.sendall(get_conf_command)
data = sock.recv(2048)
print(data)
sock.sendall(start_sending_measurements)
data = sock.recv(2048)
print(data)
while True:
sock.sendall(bytes('I do not want this', 'utf-8')) # I would like to keep receiving measurements without this
data = sock.recv(2048)
print(data)
finally:
print('Closing socket...')
sock.close()
And here is my problem:
When I run client and send command to get ID server will return ID message, then client will send command to get configuration and server will return configuration message but when I send start command server will send only one measurement and than I guess connection.recv(2048) will block execution until server gets another command. So, I added that line inside while True: loop in client script which will keep sending (unnecessary, invalid) commands and server will keep sending measurements.
How to solve this without sending commands all the time from client. I want to be able to send only one command start and server will keep sending measurements, and stop only when client sends stop command.
Also, if server receives id or cfg command while sending measurements it will first send id or cfg and than keep sending measurements.
In the server loop call select.select([connection], [connection], [connection]) (select module provides more facilities, so pick your favorite). If the socket is readable, read command and react on it. If the socket is writable (and there was a request for data), send measurements.
In case someone needs this:
def conn_handler(self, connection, address):
self.logger.info("[%d] - Connection from %s:%d", 10, address[0], address[1])
sending_measurements_enabled = False
try:
while True:
command = None
readable, writable, exceptional = select([connection], [], [], 0)
if readable:
data = connection.recv(2048)
if data:
command = get_command_from_data(data)
print("Received command %s", command)
if command == 'start':
sending_measurements_enabled = True
elif command == 'stop':
break
elif command == 'id':
connection.sendall(self.id)
elif command == 'cfg':
connection.sendall(self.cfg)
if sending_measurements_enabled:
connection.sendall(measurement)
except Exception as e:
print(e)
finally:
connection.close()
print("Connection closed")
I have a Blender code which takes sets of data from a csv file and uses them to rotate a robot arm and a human model in the Game Engine. This code works fine, but now I want to send data across a wireless connection to Blender.
I have a server code set up in Blender (which runs on Python 3)
# Server Program
# Make sure the client is being run on the data generation computer
SERVER_LOOP = True
import socket
import sys
import json
import bge
cont = bge.logic.getCurrentController()
owner = cont.owner
print ('INFO: Starting up')
# Create a TCP/IP socket to listen on
print ('INFO: Creating TCP/IP Socket')
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Prevent from 'ADDRESS ALREADY IN USE' upon restart
print ('INFO: Housekeeping...')
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind the socket to port 8081 on all interfaces
server_address = ('localhost', 8081)
print ('INFO: Binding and starting up on %s port %s' % server_address)
server.bind(server_address)
print ('INFO: Server bound')
def send_welcome(cont):
cont.send('SERVER: Welcome'.encode('utf8'))
# Listen for connectons for 5 seconds
server.listen(5)
# Connection is the SOCKET OBJECT for the connection
# Client_address is the connected peer(the client)
connection, client_address = server.accept()
print ('INFO: Connection from', connection.getpeername())
print ('INFO: Sending welcome msg')
send_welcome(connection)
print ()
while SERVER_LOOP:
# Receive data
try:
data = connection.recv(10000)
# Unless there's an error
except OSError:
print (connection)
# Decode the data into usable lists
if type(data) != type(''):
data = data.decode()
# If we want to end the client stream but keep the server running
if data=='end' or data=='End' or data=='END':
print ('INFO: Closing connection with ',connection.getpeername())
connection.shutdown(socket.SHUT_RD | socket.SHUT_WR)
print ()
connection.close()
connection, client_address = server.accept()
print ('INFO: Connection from', connection.getpeername())
print ('INFO: Sending welcome msg')
send_welcome(connection)
print ()
# If we want to stop running the server
elif data=='end server' or data=='End server' or data=='End Server':
print ()
print ('SERVER SHUT DOWN')
SERVER_LOOP = False
# Display when data is loaded back on the client side
else:
# gives feedback in server command line
data = json.loads(data)
owner['test'] = data
print ('CLIENT: %s' % data)
message = 'ping'
connection.send(('SERVER: %s' % message).encode('utf-8'))
print ('SERVER: %s' % message)
And the client code to run with it (this one runs on Python 2.7)
# Client Program
# Make sure the server is being run in Blender
import socket
import time
import json
print 'INFO: Creating Socket'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip_addr = raw_input('IP: ')
port_addr = raw_input('PORT: ')
# Type 'localhost' in the IP field
# Type '8081' in the PORT field
print 'INFO: Connecting to server'
s.settimeout(5) # Times out if 5 seconds without connecting to client
s.connect((ip_addr, int(port_addr)))
# Listen for welcome
data = s.recv(10000)
print data
print ''
while 1:
message = raw_input('CLIENT: ')
if message=='end' or message=='End' or message=='END':
print ''
print 'SHUTTING DOWN CLIENT, SERVER STILL RUNNING'
s.send(message)
break
elif message=='end server' or message=='End server' or message=='End Server':
print ''
print 'SHUTTING DOWN SERVER'
s.send(message)
break
else:
s.send(message)
data = s.recv(10000)
print data
print 'INFO: Closing socket'
s.close()
print 'INFO: Quitting'
Now, obviously this doesn't do the rotations; it's just a test script to make sure that the data transfer between the two works. And it does - in Blender's system console, the data is displayed just as I want it. However, I have a string debug property in Blender titled "test", which is supposed to display the current number just typed in the client, and it's not until I close the whole program down.
For example:
I run the server script in Blender
I run the client script in IDLE
I type in numbers on the client side
They appear in the system console on the server side, but they do NOT appear in the Game Engine
I close the server from the client side
Now, the last number I typed finally appears on the server side
So the problem is that Blender runs my script and then the Game Engine after it's done, but I want them to run concurrently.
Let me know if my explanation doesn't make sense; I can provide downloads to my stuff if need be.
I don't know if this is still a problem - you posted in February and it's now August, but I was just searching for the answer of a similar problem. Your problem is that Blender doesn't update its frames until a script has finished running. Your game is literally stuck on the first frame it plays because it starts a script as soon as that frame hits, and because of the nature of your script, never ends.
Currently, you use server.listen(5) to mean that it listens to five seconds, but the number 5 in that function refers to the backlog instead of the length of time [source]. socket.listen() will stall your game indefinitely (as far as I understand) just like an infinite loop would.
This may not be the answer you were looking for, but it's definitely an answer.
I keep getting this error
[Errno 10061] No connection could be made because the target machine actively refused it.
I'm running Windows 7 64 bit, no virus or protection software, and python is allowed through my firewall (I've also tried turning my firewall completely off but same result). When I run the server and use telnet it connects just fine. When I try to connect to the server with the client it fails. Any suggestions as to what I could try to fix this? If you need more information just ask and I'll provide.
Client Code
import socket
import sys
def main():
host = ""
port = 8934
message = "Hello World!"
host = raw_input("Enter IP: ")
#Create Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print "Failed to create socket. Error code: %s Error Message: %s"%(str(msg[0]),msg[1])
sys.exit()
print "Socket created"
#Connec to Server
print host
print port
s.connect((host,port))
print "You are connected to %s with IP adress of %s"%(host,host)
#Send Data
try:
s.sendall(message)
except socket.error:
print "Failed to send."
#Receive Data
reply = s.recv(4096)
if __name__ == "__main__":
main()
Server Code
# !usr/bin/python
import socket
import sys
HOST = ""
PORT = 8934
def main():
#Setup socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error,msg:
print "Unable to create socket"
sys.exit()
print "Socket created."
#Bind to adress
try:
s.bind((HOST,PORT))
except socket.error,msg:
print "Bind failed. Closing..."
sys.exit()
print "Socket bound."
#Start listening
s.listen(10)
print "Socket Listening"
#Accept connection
conn, addr = s.accept()
print "Connected to %s:%s"%(addr[0],addr[1])
if __name__ == "__main__":
main()
Taking a guess at your indentation, and running your code… it works just fine.* (As long as I type in 127.0.0.1 when it asks me for the IP.)
Of course the second time I run the client (if I haven't restarted the server) I get a connection-refused error. But that's just because you've coded a server that immediately quits as soon as it gets the first connection. So the second time you run the client, there is no server, so the OS rejects the connection.
You can always run the server again, which lets you run the client one more time. (Except that the server may get a 10048 error when it tries to bind the socket, because the OS is keeping it around for the previous owner. If you see that, look at SO_REUSEADDR in the docs.)
* By "works just fine" I mean that it connects, and prints out the following before quitting:
Socket created
127.0.0.1
8934
You are connected to 127.0.0.1 with IP adress of 127.0.0.1
Obviously it never sends anything to the server or receives anything back, because the server has no send or recv calls, or anything else.