我尝试制作一个连接服务器和客户端的程序。
这是服务器代码:
import socket
HOST="127.0.0.1"
PORT=5000
mySocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mySocket.bind( (HOST, PORT) )
except socket.error:
print ("Call to bind failed")
while 1:
print("Waiting for connection")
mySocket.listen(1)
connection, address=mySocket.accept()
print("Connection recieved from:", address[0])
connection.send("SERVER>>> Connection successful")
clientMessage=connection.recv(1024)
while clientMessage != "Client: end":
if not clientMessage:
break
print (clientMessage)
serverMessage=input("Server: ")
connection.send("Server: "+serverMessage)
clientMessage=connection.recv(1024)
print("Connection ended.")
connection.close()
这是客户:
import socket
HOST="127.0.0.1"
PORT=5000
print ("Attempting connection")
mySocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mySocket.connect( ( HOST, PORT) )
except socket.error:
print("Call to connect failed")
print ("Connected to server")
serverMessage=mySocket.recv(1024)
while serverMessage!="Server: end":
if not serverMessage:
break
print (serverMessage)
clientMessage=input("Client: ")
mySocket.send("Client: "+clientMessage)
serverMessage=mySocket.recv(1024)
print ("Connection ended.")
mySocket.close()
这是错误:
File "C:/Python34/python 3.4/client.py", line 13, in <module>
serverMessage=mySocket.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
错误说我做错了地址(?)
我无法理解错误对我的要求。你能救我吗?
答案 0 :(得分:1)
好吧,我对你的两个程序进行了一些编辑。您需要处理通过套接字发送和接收数据作为字节数组,因为您使用的是python 3.下面的客户端和服务器程序使用python 3.5.1为我工作。希望这会有所帮助。
此外,我摆脱了服务器中的while 1
无限循环并删除了try / except语句,因为我觉得他们没有添加任何东西。如果你打算除了socket.error之外你至少应该退出该程序,因为这是一个致命的错误。
server.py
import socket
HOST="127.0.0.1"
PORT=5000
mySocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind( (HOST, PORT) )
mySocket.listen(1)
print("Waiting for connection")
connection, address=mySocket.accept()
print("Connection recieved from:", address[0])
connection.send(bytearray("SERVER>>> Connection successful", "utf-8"))
clientMessage=connection.recv(1024)
while clientMessage != "Client: end":
if not clientMessage:
break
print (clientMessage)
serverMessage=input("Server: ")
connection.send(bytearray("Server: "+serverMessage, "utf-8"))
clientMessage=connection.recv(1024)
print("Connection ended.")
connection.close()
client.py
import socket
HOST="127.0.0.1"
PORT=5000
print ("Attempting connection")
mySocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.connect( ( HOST, PORT) )
print ("Connected to server")
serverMessage=mySocket.recv(1024)
while serverMessage!="Server: end":
if not serverMessage:
break
print (serverMessage)
clientMessage=input("Client: ")
mySocket.send(bytearray("Client: "+clientMessage, "utf-8"))
serverMessage=mySocket.recv(1024)
print ("Connection ended.")
mySocket.close()