通信使用Python的
问题描述:
插座
我做了两个脚本在Python中使用套接字来的做法,但我已经建立了连接后,通信故障: 我下面的脚本:通信使用Python的
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
客户端的.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()
当我执行两个脚本我有以下结果:
服务器:
myPrompt : ./Server.py &
Server ready, waiting for request...
Client connected, adresse IP myIP, port 53551
客户:
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
看来,我的消息作为bash命令,而不是发送消息执行。但是,如果我再次运行工作,将工作:
客户:
myPrompt : %
./Client.py
hello
服务器:
C> hello
S>
但之后再次失败。任何时候我想发送消息时,我都必须再次运行这项工作。
你知道错误在哪里吗?
答
其实问题出在脚本启动。您可以使用下面的命令
./Client.py &
随着&
进程在后台启动,这样你就可以继续使用外壳。 &
从终端卸载您的脚本stdin
。在脚本启动后在终端中打印的所有内容都将被解释为bash命令。
尝试使用刚刚
./Client.py
我想你的代码'raw_input',而不是'input'它完美地工作 –