我正在尝试创建一个使用p2p(点对点)连接的基本即时消息程序,因此它不需要服务器。我很确定没有错,但每次运行我创建的客户端程序时,都会收到此错误: s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) NameError:未定义全局名称“SOL_SOCKET” 这是程序:
import socket
def Receiver():
# Create socket that supports IPv4, TCP Protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created."
# Requests for IP of host (DNS)
dns = "localhost"
HOST = ''
PORT = 25395
try:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
except socket.error as serror:
print "socket error"
s.bind((HOST, PORT)) # Listens on all interfaces...
print 'Listening on port 25565'
s.listen(True) # Listen on the newly created socket...
conn, addr = s.accept()
print 'Connected in port 25565'
data = conn.recv(1024)
print data
s.close()
def Sender():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dns = "localhost"
HOST = socket.gethostbyname(dns)
port = 25565
# Connect to server
s.connect((host,port))
print "Socket connected to " + dns + " on IP " + host
# Assign message to be sent to server to a variable
message = raw_input("Message to be sent to server: ")
#Send the actual message to server
s.sendall(message)
print "Message sent successfully"
s.close()
input = raw_input('S is send, R is receive: ')
if input == 's':
Sender()
if input == 'r':
Receiver()
我已经尝试删除s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1),但它告诉我,当没有2个套接字使用同一个端口时,我不能在同一个端口上使用2个套接字。
答案 0 :(得分:6)
在您的代码中:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
喜欢:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# ^^^^ added ^^^
因为您只导入了socket
,请检查以下代码:
>>> import socket
>>> SOL_SOCKET
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'SOL_SOCKET' is not defined
>>> socket.SOL_SOCKET
1