Python Sockets Question

Maboroshi nobody at hotmail.com
Tue Oct 26 12:47:36 EDT 2004


Hi I am building a simple chat program but I am running into problems 
interacting with more than one client I can send a message to a server 
and it can recieve it no problem but how do I get more than one client 
to see the messages as well so clients can talk to eachother basically 
how do I get the server to send the messages back so all the clients can 
see it

Here is my code

The Server ------------------------------------------------------------

import socket
# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
	data,addr = UDPSock.recvfrom(buf)
	if not data:
		print "Client has exited!"
		break
	else:
		print "\nReceived message '", data,"'"

# Close socket
UDPSock.close()



The Client ------------------------------------------------------------

from Tkinter import *
import socket

# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)


class App(Frame):
     def send(self):
         # Send messages
         while (1):
             data = self.entry.get()
             if not data:
                 break
             else:
                 if(UDPSock.sendto(data,addr)):
                     break


     def disconnect(self):
         # Close socket
         UDPSock.close()

     def __init__(self, master=None):
         Frame.__init__(self, master)
         self.pack(fill=BOTH, expand=True)

         self.createWidgets()

     def createWidgets(self):
         self.scrollbar = Scrollbar(self)
         self.scrollbar.grid(row=0, column=1, sticky=N+S)
         self.rowconfigure(0, weight=1)
         self.columnconfigure(0, weight=1)
         self.listbox = Listbox(self)
         self.listbox.grid(row=0, column=0, sticky=N+E+S+W)
         self.listbox.config(yscrollcommand=self.scrollbar.set)
         self.scrollbar.config(command=self.listbox.yview)
         self.entry = Entry(self)
         self.entry.grid(row=1, column=0, columnspan=2, sticky=E+W)


         self.top = top = Toplevel()
         top.title("Chat Client")
         top.maxsize(100, 50)
         top.minsize(100, 50)
         self.execute = Button(top, text="Send", command=self.send)
         self.execute.grid(row=1, column=0, sticky=E+W)
         self.disconnect = Button(top, text="Disconnect", 
command=self.disconnect)
         self.disconnect.grid(row=2, column=0, sticky=E+W)

app = App()
app.master.title("Chat Client")
app.master.minsize(400, 300)
app.master.maxsize(600, 500)
app.mainloop()




More information about the Python-list mailing list