【发布时间】:2018-05-22 05:11:26
【问题描述】:
我有两个脚本正在积极用于编程课程。我的代码注释很好,我的老师更喜欢外部资源,因为有很多不同的解决方案。
但要解决实际问题,我需要创建一个带套接字的服务器(可以使用),然后允许另一台计算机使用单独的脚本(也可以使用)连接到它。问题是在建立连接之后。我希望两者能够来回发送消息。它发送的方式必须是字节形式,我是如何设置的,但返回的字节无法读取。我可以对其进行解码,但我希望它与其他所有内容一起方便地位于命令提示符中。我尝试将主脚本 (Connection.py) 导入辅助脚本 (Client.py),但随后它运行主脚本。有什么办法可以阻止它运行吗?
这是我的主脚本(创建服务器的那个)
#Import socket and base64#
import socket
import base64
#Creating variable for continuous activity#
neverland = True
#Create socket object#
s = socket.socket()
print ("Socket created") #Just for debugging purposes#
#Choose port number for connection#
port = 29759 #Used a random number generator to get this port#
#Bind to the port#
s.bind((' ', port))
print ("Currently using port #%s" %(port)) #Just for debugging purposes#
#Make socket listen for connections#
s.listen(5)
print ("Currently waiting on a connection...") #Just for debugging purposes#
#Loop for establishing a connection and sending a message#
while neverland == True:
#Establish a connection#
c, addr = s.accept()
print ("Got a connection from ", addr) #Just for debugging purposes#
#Sending custom messages to the client (as a byte)#
usermessage = input("Enter your message here: ")
usermessage = base64.b64encode(bytes(usermessage, "utf-8"))
c.send(usermessage)
#End the connection#
c.close()
这是我的辅助脚本(连接到主脚本的那个)
#Import socket module#
import socket
import Connection
#Create a socket object#
s = socket.socket()
#Define the port on which you want to connect#
port = 29759
#Connect to the server on local computer#
s.connect(('127.0.0.1', port))
#Receive data from the server#
print (s.recv(1024))
usermessage = base64.b64decode(str(usermessage, "utf-8"))
print (usermessage)
#Close the connection#
s.close()
在命令提示符下运行它们时,会出现以下错误:
它尝试再次运行主脚本并得到错误,我该如何防止它?
【问题讨论】:
标签: python