我已经创建了一个聊天服务器客户端,但是当我运行它时,我收到了这个错误:
Traceback (most recent call last):
File "C:/Users/Public/Documents/Programming/Chat Client/Chat Client.py", line 21, in
<module>
s = socket.socket((socket.AF_INET, socket.SOCK_STREAM))
AttributeError: type object 'socket' has no attribute 'socket'
我没有看到问题所以任何人都可以帮助我,这是我的代码:
# Import Modules
from tkinter import *
from socket import *
from threading import *
# Window Setup
root = Tk()
root.title('Chat Client')
root.state('zoomed')
# Chat Variables
global s
s = socket.socket((socket.AF_INET, socket.SOCK_STREAM))
s.connect((TARGET, DEFAULT_PORT))
enter = StringVar()
TARGET = s.gethostname()
DEFAULT_PORT = 45000
# Chat Message Box Setup
chat = Text(root, height=31, state=DISABLED)
entry = Entry(root, fg='blue', textvariable=enter, width=200)
scroll = Scrollbar(root)
chat['yscrollcommand'] = scroll.set
scroll['command'] = chat.yview
scroll.pack(side=RIGHT, fill=Y)
chat.pack(side=TOP, fill=X)
entry.pack(side=BOTTOM)
# Send Command
def send(event):
msg = enter.get()
chat['state'] = NORMAL
chat['fg'] = 'blue'
chat.insert(END, ('You: ' + msg + '\n'))
while 1:
s.sendall(msg)
chat['state'] = DISABLED
chat['fg'] = 'black'
enter.set('')
s.close()
entry.bind('<Return>', send)
def recieve():
s.bind((TARGET, DEFAULT_PORT))
s.listen(True)
conn, addr = s.accept()
while True:
data = conn.recv(1024)
chat['state'] = NORMAL
chat['fg'] = 'red'
chat.insert(END, ('Stranger: ' + data + '\n'))
thread.start(recieve, ())
thread.start(send, ())
root.mainloop()
我不确定我的代码有什么问题,所以有人可以帮助我吗?
提前致谢!
答案 0 :(得分:1)
from socket import *
您已导入整个socket
模块。那里的 没有socket.socket
。您已将socket
对象直接导入当前名称空间。
要访问它,只需执行
s = socket((socket.AF_INET, socket.SOCK_STREAM))
如果你已经完成了
import socket
然后,您可以通过模块命名空间访问socket
对象。