Dan Alexander
Dan Alexander

Reputation: 2072

Socket chat client error

I have made a chat server client but when I run it I get this error:

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'

I don't see the problem so can anyone help me, here is my code:

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

I am not sure what is wrong with my code so could anyone please help me?

Thanks In Advance!

Upvotes: 0

Views: 152

Answers (1)

Joel Cornett
Joel Cornett

Reputation: 24788

from socket import *

You've imported the entire socket module. There is no socket.socket. You've imported the socket object directly into the current namespace.

To access it, simple do

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

If you had done

import socket

Then you could access the socket object via the module namespace.

Upvotes: 1

Related Questions