在Python上使用套接字进行通信

时间:2017-10-28 18:25:19

标签: python bash sockets scripting

我已经制作了两个脚本来练习在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

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()

当我执行这两个脚本时,我得到以下结果:

服务器:

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> 

但它之后再次失败。每当我想发送信息时,我都必须再次运行这份工作。

你知道错误在哪里吗?

1 个答案:

答案 0 :(得分:0)

实际上问题在于脚本启动。您使用以下命令

./Client.py &

使用&进程在后台启动,因此您可以继续使用shell。 &从终端分离stdin您的脚本。在脚本启动后在终端中打印的所有内容都将被解释为bash命令 尝试使用

./Client.py