
July 10th, 2003, 08:24 AM
|
|
Registered User
|
|
Join Date: Jul 2003
Location: A:\
Posts: 17
Time spent in forums: 5 m 13 sec
Reputation Power: 0
|
|
|
Socket and Threading help
This is my first dive into the world of sockets and threading. I've tried to make a basic chat server and client, and it worked, kinda, untill i tried to get both sending and receiving at once. So i started to use threading. The server works fine(i think), so it's the client that's messing up. Anyway, here's the code:
Code:
#server.py
from socket import *
from threading import *
chatlist={}
threadlist={}
try:
timeout=int(raw_input('Set Timout: '))
except:
timeout=1
def threadFunction(*args):
chat=args[0]
chat.name=chat.socket.recv(10)
name=chat.name
enter=name+' has entered the chat'
chat.send(enter)
while chat.recv != '/exit':
try:
chat.recv=chat.socket.recv(1000)
if chat.recv=='/exit':
leave=name+' has disconnected'
chat.send(leave)
chat.socket.close()
elif chat.recv:
chat.send(chat.name+': '+chat.recv)
except:
pass
class chatter:
def __init__(self, socket, location):
self.socket=socket
self.address, self.port=location
self.recv=None
print 'Class Init...'
def send(self, data):
for i in chatlist.keys():
chatlist[i].send(data)
print "Sent: "+data
s=socket(AF_INET, SOCK_STREAM)
print 'Server Init...'
print 'Timeout set to '+str(timeout)+' seconds...'
s.bind(('', 90))
'Server Bound...'
s.listen(10)
print 'Waiting for connections.'
while 1 == 1:
try:
s.settimeout(timeout)
NewSocket, location=s.accept()
s.settimeout(None)
print 'Connected from '+str(location)
chatlist[len(chatlist)+1]=NewSocket
chatclass=chatter(NewSocket, location)
threadlist[len(threadlist)+1]=Thread(name=str(location), target=threadFunction, args=[chatclass])
threadlist[len(threadlist)].start()
print 'Thread Started'
except:
pass
Code:
#client.py
from socket import *
from Tkinter import *
import tkSimpleDialog
import threading
import sys
def connect(name):
s=socket(AF_INET, SOCK_STREAM)
s.connect(('halabaladu.hopto.org', 90))
print 'Connected to server...'
s.settimeout(1)
print 'Setting timeout...'
s.send(name)
print 'Name sent...'
return s
def listen(*args):
print 'Using Socket:'
print args
socket=args[0]
print 'Aquired Socket handler...'
recv=None
print 'Resetting Receive Buffers...'
while recv != '/exit':
try:
recv=socket.recv(6000)
except:
recv=None
if recv:
po(recv+'\n')
else:
pass
def po(t):
text.insert(END, t)
def send():
snd=input.get()
socket.send(snd)
if snd == '/exit':
socket.close()
sys.exit()
else:
pass
root=Tk()
text=Text(root, width=110)
text.grid(columnspan=2)
input=StringVar(root)
chat=Entry(root, textvariable=input, width=100)
chat.grid()
button=Button(text='Send', command=send, width=10)
button.grid(column=1, row=1)
po('This is a TEST!\n')
name=tkSimpleDialog.askstring('Nickname', 'Enter your nickname:')
if name:
socket=connect(name)
receive=threading.Thread(name='Receiver', target=listen, args=[socket])
print 'Setting up thread...'
receive.start()
print 'Thread Started'
else:
pass
|