Creating a socket in python

末鹿安然 提交于 2019-12-25 04:08:03

问题


import socket
import sys

HOST = ''   # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#wait to accept a connection - blocking call
conn, addr = s.accept()

#display client information
print 'Connected with ' + addr[0] + ':' + str(addr[1])

While running this file I get

  File "socket.py", line 1, in <module>
    import socket
  File "/root/socket.py", line 7, in <module>
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
AttributeError: 'module' object has no attribute 'AF_INET'

I want to create a socket to accept connections and read/send data... Im experiencing this kind of error while doing it. I am new to python i dont know anything i just got the code from a website. thankyou


回答1:


You called your file socket.py rename it to somethng like my_socket.py and delete the socket.pyc file in the same directory.

You are trying to import from your socket.py file not the actual socket module, python checks the local directory first.




回答2:


The error simply means that the socket object does not have an error field or attribute

I think it is a naming issue you have since you names your file as the name of socket module. Change the name, might fix the problem.



来源:https://stackoverflow.com/questions/27714497/creating-a-socket-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!