0

我已经制作了一个聊天服务器客户端,但是当我运行它时,我收到了这个错误:

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()

我不确定我的代码有什么问题,所以有人可以帮助我吗?

提前致谢!

4

1 回答 1

1
from socket import *

您已经导入了整个socket模块。没有。_ _ socket.socket您已将socket对象直接导入当前命名空间。

要访问它,只需执行

s = socket((socket.AF_INET, socket.SOCK_STREAM))

如果你做了

import socket

然后您可以socket通过模块命名空间访问该对象。

于 2013-07-17T07:48:42.963 回答