How to send and receive messages on a server socket? - python

I am trying to create a simple "chat room" of the sort, where I do not know how many messages I will get from a client but my server will receive them all, display them and eventually respond. The problem is that when I click on the respond textbox, my code crashed. I am really unsure about where my problem lies and any help will work.
from Tkinter import *
import tkMessageBox
import socket
import threading
# Global variables
SendConfirmation = "0"
ConnectionConfirmation = "0"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
data_old = ""
# Initiates socket and connection
def ConnectBind():
global ConnectionConfirmation
global sock
server_address = (IP_Entry.get(), int(Port_Entry.get()))
sock.bind(server_address)
tkMessageBox.showinfo("Bind Successful", "Connected to " + IP_Entry.get() + " at port " + Port_Entry.get())
ConnectionConfirmation = "1"
# Sets the disconnect signal
def DisconnectBind():
global ConnectionConfirmation
ConnectionConfirmation = "2"
# Sets the Send Signal
def SendMessage():
global SendConfirmation
SendConfirmation="1"
# Running background listen
def BackgrounListen():
global data_old
data = connection.recv(1024)
if data != None:
if data != data_old:
Message_Text.insert('1.0', data + '\n')
# Window set up
root = Tk()
root.title('TCP/IP software')
ConnectionFrame = Frame(root)
ConnectionFrame.pack(side=TOP, fill=X)
SendFrame = Frame(root)
SendFrame.pack(side=TOP, fill=X)
MessageFrame = Frame(root)
MessageFrame.pack(side = BOTTOM)
# Connection information frame
IP_Label = Label(ConnectionFrame, text="IP address: ")
IP_Entry = Entry(ConnectionFrame, bd=10, text="Enter IP address here")
Port_Label = Label(ConnectionFrame, text="Port number: ")
Port_Entry = Entry(ConnectionFrame, bd=10, text="Enter port number here")
IP_Label.grid(row=0, column=0)
IP_Entry.grid(row=0, column=1)
Port_Label.grid(row=1, column=0)
Port_Entry.grid(row=1, column=1)
# Connect and bind to the address and port
Connect_Button = Button(ConnectionFrame, text="Connect", command=ConnectBind)
Connect_Button.grid(row=3, column=0)
DisConnect_Button = Button(ConnectionFrame, text="Disconnect", command=DisconnectBind)
DisConnect_Button.grid(row=3, column=1)
# Send messages frame
SendMessage_Entry = Entry(SendFrame, bd=10, text="Type your message here")
SendMessage_Button = Button(SendFrame, text="Send Message", command=SendMessage)
SendMessage_Entry.pack()
SendMessage_Button.pack()
# Information/Messages display frame
Message_Text = Text(MessageFrame, height=8, width=50)
Message_Scroll = Scrollbar(MessageFrame)
Message_Text.pack(side=LEFT, fill=Y)
Message_Scroll.pack(side=RIGHT, fill=Y)
Message_Scroll.config(command=Message_Text.yview())
Message_Text.config(yscrollcommand=Message_Scroll.set)
# Start the GUI before running
root.update_idletasks()
root.update()
#Working out main
Message_Text.insert(INSERT, "Software started")
while ConnectionConfirmation != "2":
if ConnectionConfirmation == "1":
sock.listen(1)
connection, client_address = sock.accept()
Message_Text.insert('1.0', "Client connected\n")
connection.sendall("connected to server")
root.update_idletasks()
root.update()
while ConnectionConfirmation == "1":
if connection.recv#:
# if SendConfirmation == "1":
# connection.send(SendMessage_Entry.get())
# SendConfirmation = "0"
background_thread = threading.Thread(target=BackgrounListen())
background_thread.daemon = True
background_thread.start()
root.update_idletasks()
root.update()
elif ConnectionConfirmation == "2":
sock.close()
#Message_Text.insert('1.0', "Socket properly closed")
#ConnectionConfirmation = "0"
#root.update_idletasks()
#root.update()
root.update_idletasks()
root.update()

the easiest way is to make the chat room like a reverse shell .
i write the code here .
hope to be helpful. ;-)
[CODE] : server.py
import socket
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
ip = socket.gethostname()
port = 4444
s.bind((ip , port))
name = input("Enter Your Name : ")
try :
while True :
s.listen(5)
conn , addr = s.accept()
print("Connection From : ",addr)
while True :
data = conn.recv(1024)
print()
print(data)
print()
msg = input("Enter the Massage : ")
msg = name + " : " + msg
if msg == "exit" :
conn.close()
s.close()
break
else :
conn.send(bytes(msg , "UTF-8"))
except IOError as error :
print("\n [!] Connection Faild [!] \n",error)
conn.close()
s.close()
[CODE] : client.py
import socket
ip = socket.gethostname() #ip to connect
port = 4444
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
name = input("Enter Your Name : ")
try :
s.connect((ip , port))
print("[+] Connected to : " , ip)
while True :
print()
cmd = input("Enter the Massage : ")
if cmd == "exit" :
s.close()
break
exit()
else :
cmd = name + " : " + cmd
s.send(bytes(cmd , "UTF-8"))
data = s.recv(1024000)
data = strings.byte2str(data)
print()
print(data)
except IOError as error :
print("\nDisconnected From : ",ip,"\n",error)
s.close()
have a good time :-)

Related

Decoding data sent through a TCP socket in Python

I have a basic program where in a Tkinter window a user presses a button that generates a string in a listbox. Using a second send button, I want to transfer those strings through a socket server to a second client. The message printed to the console at the point of departure (client1) is a tuple, and it can be iterated through with a for loop to make it more legible i.e. each element is printed to a new line. Using a print function at the point of arrival (client2), the same tuple is produced, but trying to use a for loop on it iterates through each character in the group of strings, as opposed to each element of the tuple as desired.
This is client1:
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
from tkinter import messagebox
from tkinter import scrolledtext
from tkinter import ttk
from tkinter import font
import os
import datetime
import pickle
def receive():
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
except OSError: # Possibly client has left the chat.
break
def send(event=None): # event is passed by binders.
global sent
global current_datetime
global order_list
sent = order_list.get(0, END)
msg = sent
for i in msg:
print(i)
client_socket.send(bytes(str(msg), "utf8"))
if msg == "{quit}":
client_socket.close()
window.quit()
order_list.delete(0, END)
window = tkinter.Tk()
window.title("Title")
window.geometry("1280x1080")
var = IntVar()
var.set(1)
check_Table_Button = False
font = font.Font(family="Arial", size=9, weight="bold")
height = 4
width = 7
padx = 8
pady = 1
order_list=Listbox(window, width=35, height = 35)
order_list.config(font=font)
order_list.grid(row =0, column = 11, columnspan=3, rowspan=8)
def clickedTable(table):
# print(table)
order_list.insert(END, table)
global check_Table_Button
check_Table_Button = True
def addTable(table, number, x) #Sample Button to generate string
table = table
btn_masa_x = Button(window, text=str(table),font=font,
bg="orange", fg="black",
command=lambda: clickedTable(table),
height=height, width=width,
padx=padx+1, pady=pady)
btn_masa_x.grid(column=x, row=number, rowspan=1, columnspan=1)
addTable("Table 1 ", 0, 0)
def send_button():#Second button to send over socket
send_button =Button(window, text="Send",
font=font, bg="lime green",
command=lambda: send(),
height=height, width=width,
padx=padx, pady=pady)
send_button.grid(column=10, row = 8, rowspan=1)
send_button()
HOST = "127.0.0.1"
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
window.mainloop()
This is the server:
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
# client.send(bytes("Greetings from the cave! Now type your name and press enter!", "utf8"))
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
def handle_client(client): # Takes client socket as argument.
"""Handles a single client connection."""
name = client.recv(BUFSIZ).decode("utf8")
# welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name
# client.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat!" % name
# broadcast(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFSIZ)
if msg != bytes("{quit}", "utf8"):
broadcast(msg)
# broadcast(msg, name + ": ")
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s has left the chat." % name, "utf8"))
break
def broadcast(msg, prefix=""): # prefix is for name identification.
"""Broadcasts a message to all the clients."""
for sock in clients:
sock.send(bytes(prefix, "utf8") + msg)
clients = {}
addresses = {}
HOST = '127.0.0.1'
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
And this is client2:
from threading import Thread
import tkinter
import pickle
def receive():
"""Handles receiving of messages."""
while True:
try:
msg =client_socket.recv(BUFSIZ)#.decode("utf-8")
msg = pickle.loads(msg)
print(msg)
# msg_list.insert(tkinter.END,msg)
except OSError: # Possibly client has left the chat.
break
def send(event=None): # event is passed by binders.
"""Handles sending of messages."""
msg = my_msg.get()
my_msg.set("") # Clears input field.
client_socket.send(bytes(msg, "utf8"))
if msg == "{quit}":
client_socket.close()
top.quit()
def on_closing(event=None):
"""This function is to be called when the window is closed."""
my_msg.set("{quit}")
send()
top = tkinter.Tk()
top.title("Chatter")
messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar() # For the messages to be sent.
scrollbar = tkinter.Scrollbar(messages_frame) # To navigate through past messages.
# Following will contain the messages.
msg_list = tkinter.Listbox(top,width=40,height=10)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
messages_frame.pack()
entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()
top.protocol("WM_DELETE_WINDOW", on_closing)
#----Now comes the sockets part----
# HOST = input('Enter host: ')
HOST = "127.0.0.1"
# PORT = input('Enter port: ')
PORT = 33000
if not PORT:
PORT = 33000
else:
PORT = int(PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
tkinter.mainloop()
As I said above, the msg variable in client2, the one that receives the message, is printed as a tuple but a for loop will iterate over each character of the strings contained.
Using the pickle module I received two separate errors.
When I pass .decode("utf-8) and then .loads() it says "Could not find MARK).
Without the .decode(), the error is "unpickling stack underflow".
My desired outcome is for each of the individual strings that arrive over the TCP socket to be added to the listbox in client2 on a new line, and without the ('', '') symbols.
Should I try to convert it to a .json object?
Or will another networking module produce better results?
I'm sorry about the length of code and the potentially obvious answer. Beginner to networking.

Is there a way to limit the number of messages/second the client is sending in a Python chatroom application?

I am making a python chatroom application for school with a functioning clientside and serverside script. I am now adding multiple functionalities to the chatroom to make it easier to use, one of which is hopefully spam protection. Is there a way I can record how many messages per a certain measurement of time the client is sending and if they go over the maximum they are muted for a certain amount of time?
clientside.py:
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import tkinter as tkinter
#import tkinter.ttk as ttk
#from ttkthemes import ThemedStyle
from tkinter import END
from datetime import *
import time as tme
def receive():
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
msg_list.insert(tkinter.END, '[' + current_time + '] ' + msg)
msg_list.yview(END)
msg_list.yview()
except OSError:
break
def send(event=None):
msg = my_msg.get()
if msg.isspace() != True:
my_msg.set("")
client_socket.send(bytes(msg, "utf8"))
msg_list.yview(END)
msg_list.yview()
elif msg.isspace() == True:
my_msg.set("")
if msg == "{quit}":
client_socket.close()
top.quit()
def on_closing(event=None):
top.destroy()
my_msg.set("{quit}")
send()
top.quit()
top = tkinter.Tk()
top.resizable(width=False, height=False)
#top.iconbitmap('C:/Users/Ethen Dixon/Downloads/filled_chat_aH2_icon.ico')
top.title("Chat Room 90")
#style = ThemedStyle(top)
#style.set_theme("equilux")
messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar()
my_msg.set("[type here]")
scrollbar = tkinter.Scrollbar(messages_frame)
msg_list = tkinter.Listbox(messages_frame, height=30, width=100, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
msg_list.pack()
messages_frame.pack()
entry_field = tkinter.Entry(top, textvariable=my_msg, width=100)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()
top.protocol("WM_DELETE_WINDOW", on_closing)
HOST = input('Enter host: ')
PORT = input('Enter port: ')
if not PORT:
PORT = 33000
else:
PORT = int(PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
tkinter.mainloop()
serverside.py:
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
client.send(bytes("Welcome to Chat Room 90! Please type in your username and press enter.", "utf8"))
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
def handle_client(client):
"""Handles a single client connection."""
name = client.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s!' % name
client.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat!" % name
broadcast(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFSIZ)
if msg != bytes("{quit}", "utf8"):
broadcast(msg, name+": ")
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s has left the chat." % name, "utf8"))
break
def broadcast(msg, prefix=""):
"""Broadcasts a message to all the clients."""
for sock in clients:
sock.send(bytes(prefix, "utf8")+msg)
clients = {}
addresses = {}
HOST = ''
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
A way to do this is using the widget.unbind(sequence, funcid = None) method.
This, as the name suggests, deletes the bindings on w for a determined event.
Then you can use the tkinter built-in method root.after() to call a function that you create to rebind the button to the function.
But for this to work you need to bind the send_button using the .bind() method.
def rebind():
send_button.bind("<Button-1>", send)
send_button.bind("<Button-1>", send)
send_button.unbind("<Button-1>", funcid=None)
top.after(time in miliseconds, rebind)

Tkinter entry returns ValueError: invalid literal for int() with base 10: '' [duplicate]

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 4 years ago.
So today I've been working on a new GUI with tkinter and came across and issue with parsing a string from an entry into an int and I get this error.
Traceback (most recent call last):
File "/Users/g.shiner21/Desktop/Python/P2PFile/P2PFileServer.py", line 47, in <module>
bStartServer = Button(f1, text="Start Server", command=startServer(host))
File "/Users/g.shiner21/Desktop/Python/P2PFile/P2PFileServer.py", line 28, in startServer
intport = int(port)
ValueError: invalid literal for int() with base 10: ''
Here is the function,
def startServer(host):
port = ePort.get()
intport = int(port)
s = socket.socket()
s.bind((host, intport))
s.listen(4)
The most confusing part is that when I test something like this,
strTest = "10000"
intTest = int(strTest)
I get no errors. So I don't think I'm doing my parsing wrong. But at this point I'm not too sure. Any help would be greatly appreciated! :)
Edit: For those that it helps here is the full program(or at least what I have so far. I commented out the second part of it while I was building the GUI because I didn't want to have to deal with any interferences.
# server.py
import socket # Import socket module
import sys
from tkinter import *
from tkinter import ttk
port = 0 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = "0.0.0.0"
root=Tk()
root.title("Test Window")
c = '#ececec'
n = ttk.Notebook(root) #Create notebook
f1 = ttk.Frame(n) #Create frames for notebook
f2 = ttk.Frame(n)
f3 = ttk.Frame(n)
n.add(f1, text='Server') #Add frames to notebook
n.add(f2, text='File')
n.add(f3, text='Playback')
n.pack(expand=1, fill='both') #Pack notebook
def startServer(host):
port = ePort.get()
intport = int(port)
s = socket.socket()
s.bind((host, intport))
s.listen(4)
lservType = Label(f1, text="Select Server Type: ", bg=c)
lservType.grid(columnspan=2, row=0)
R1 = Radiobutton(f1, text="Local Host", variable=host, value="localhost", bg=c)
R1.grid(row=1, column=0)
R2 = Radiobutton(f1, text="Wireless Host", variable=host, value="0.0.0.0", bg=c)
R2.grid(row=1, column=1)
lPort = Label(f1, text="Port: ", bg=c)
ePort = Entry(f1)
lPort.grid(row=2, column=0, sticky='e')
ePort.grid(row=2, column=1)
bStartServer = Button(f1, text="Start Server", command=startServer(host))
bStartServer.grid(row=3, columnspan=2)
"""
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = "0.0.0.0" # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(4) # Now wait for client connection.
#print("Your IP address is: " + socket.gethostbyname(socket.gethostname()))
print ('Server listening....')
while True:
conn, addr = s.accept() # Establish connection with client.
` print ('Got connection from', addr)
input ('Press the enter key to send')
filename = 'send.mov'
print ('File Assigned')
f = open(filename,'rb')
print ('File Oppened')
l = f.read(131072)
print ('Reading')
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(131072)
print ('Reading')
f.close()
print('Done sending')
conn.close()
#sys.exit()
"""
root.mainloop()
You get this error when the python can't cast the variable to int. make sure "port" is an integer and the try casting that to int. the second example works fine because your hard coding the value of input and it's an integer. You can update your function as follows:
def startServer(host):
try:
port = ePort.get()
intport = int(port)
s = socket.socket()
s.bind((host, intport))
s.listen(4)
except BaseException:
print('wrong entry')

running file opening dialog of server using tkFileDialog on client

I am trying to make a simple system to transfer a file from server to client.
I want to show the client a file open dialog using tkFileDialog.
The problem is when I run the client & server the dialog box gets opened in server rather than client. I thought about send the object of tkFileDialog via
con.send(str(tkFileDialog.askopenfilename(initialdir='~', title='Choose a text file/program')))
If someone could help me out with this it will be really helpful or if someone has a better idea to open server filesystem in client without ssh
The full code is
server.py:
import socket,os
import Tkinter,tkFileDialog,tkMessageBox
def startServer(portName,ip):
if portName != '' and ip != '':
tkMessageBox.showinfo('Server Started','Server running!!! ok will be enabled after transfer')
port = int(portName)
ipName = ip
sd = socket.socket()
sd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #reuse socket
sd.bind((ipName, port))
sd.listen(50)
con, addr = sd.accept()
print ' connection from ' + str(addr)
con.send(tkMessageBox.showinfo('connected', 'Connection Successful'))
while True:
con.send(str(tkFileDialog.askopenfilename(initialdir='~', title='Choose a text file/program')))
fileN = con.recv(1024)
if os.path.isfile(fileN):
con.send(tkMessageBox.showinfo('Process completed', 'Rerun server to transfer again'))
con.send('exists')
fileN = str(fileN)
#read contents
fd = open(fileN, 'r')
buff = fd.read()
print buff
print len(buff)
fd.close()
#send contents
con.send(str(len(buff)-1))
print con.recv(14) #acknowledgement of length received
con.send(buff)
break
else:
con.send(tkMessageBox.showerror('Failed', 'Select appropriate file'))
con.send('ne')
sd.close()
else:
tkMessageBox.showerror('Failed','Failed to start server. Give appropriate inputs')
def main():
root = Tkinter.Tk()
root.geometry('300x200')
root.title('Server')
ipLabel = Tkinter.Label(root,text='\nEnter IP Address of server\n')
portLabel = Tkinter.Label(root, text='\nEnter Port Address of server\n')
ipEntry = Tkinter.Entry(root)
portEntry = Tkinter.Entry(root)
connectButton = Tkinter.Button(root,
text='Run',
command=lambda: startServer(portEntry.get(), ipEntry.get())
)
ipLabel.pack()
ipEntry.pack()
portLabel.pack()
portEntry.pack()
connectButton.pack()
root.mainloop()
main()
the client.py:
import socket
import Tkinter,tkMessageBox
def establishConnection(ipEntry,portEntry,root):
if ipEntry != '' and portEntry != '':
port = int(portEntry)
ipName = str(ipEntry)
sd = socket.socket()
sd.connect((ipName, port))
# ack if connection established
sd.recv(1024)
while True:
#file select dialog
fileN = sd.recv(1024)
sd.send(fileN) #send file name to open
sd.recv(1024) #dialog after file selected or not
fileAck = sd.recv(6) #acknowledge if file correct
if fileAck == 'exists':
leng = int(sd.recv(10))
sd.send('length recieved')
buff = str(sd.recv(leng))
saveLabel = Tkinter.Label(root, text='\n\nSave with Name\n')
saveNameEntry = Tkinter.Entry(root)
saveButton = Tkinter.Button(root,
text='SAVE',
command=lambda: saveFile(saveNameEntry.get(), buff, root))
saveLabel.pack()
saveNameEntry.pack()
saveButton.pack()
break
sd.close()
def saveFile(fileN, buff, root):
fd = open(fileN, 'w')
fd.write(buff)
fd.close()
tkMessageBox.showinfo('Operation Complete','file saved as '+fileN)
root.destroy()
def main():
root = Tkinter.Tk()
root.geometry('300x600')
root.title('Client')
ipLabel = Tkinter.Label(root,text='\nEnter IP Address of server\n')
portLabel = Tkinter.Label(root, text='\nEnter Port Address of server\n')
ipEntry = Tkinter.Entry(root)
portEntry = Tkinter.Entry(root)
connectButton = Tkinter.Button(root,
text='Connect',
command=lambda: establishConnection(ipEntry.get(), portEntry.get(),root)
)
ipLabel.pack()
ipEntry.pack()
portLabel.pack()
portEntry.pack()
connectButton.pack()
root.mainloop()
main()
The file dialog works only for the system that opens it. You can't use it to pick files on a remote system.

Python - Chat 2nd client doesn't receive anything until it sends

Was trying to make a chat application written in Python, but for some reasons I don't know, when the 1st client sends data, it works but the 2nd or other client can't receive it until the other client tries to send a message and it works fine...
Here's my code for the client:
from Tkinter import *
from PIL import ImageTk, Image
from socket import *
from threading import Thread, Lock
import time
'#Connect to Server'
shutdown = False
host = "127.0.0.1"
port = 0
server = ("127.0.0.1", 12345)
s = socket(AF_INET, SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
global alias
def sendmsg():
msg = alias + " : " + chatEntry.get("0.0", END).strip() + "\n"
#chatLog.config(state=NORMAL)
#chatLog.insert(END, msg)
chatEntry.delete(1.0, END)
#chatLog.config(state=DISABLED)
s.sendto(msg, server)
def recvmsg(name, sock):
while not shutdown:
try:
while True:
data = sock.recv(1024)
chatLog.config(state=NORMAL)
chatLog.insert(END, str(data))
chatLog.config(state=DISABLED)
print str(data)
except:
pass
alias = raw_input("Alias ==> ")
root = Tk()
'#Create a window'
frame = Frame(root, width=600, height=450, bg="black")
frame.pack()
'#Create a chat log'
chatLog = Text(root, font=("Determination Sans", 12))
chatLog.insert(END, "Connecting..... \n")
chatLog.config(state=DISABLED)
chatLog.place(x=13, y=13, width=425, height=329)
'#Create list of friends online'
friendsList = Text(root)
friendsList.config(state=DISABLED)
friendsList.place(x=445, y=13, width=142, height=329)
'#Create an entry where you can enter your message'
chatEntry = Text(root)
chatEntry.place(x=13, y=349, width=425, height=96)
'#Create a send button'
btnLogin = Button(root, text="SEND", command=sendmsg)
btnLogin.place(x=445, y=349, width=142, height=96)
'#Set it fixed, not resizable......'
root.resizable(width=FALSE, height=FALSE)
root.wm_title("Chat - Underchat")
Thread(target=recvmsg, args=("RecvThread", s)).start()
root.mainloop()
And here's my code for the server:
from socket import *
import time
'#Put IP here...'
'#Put Socket here...'
host = "127.0.0.1"
port = 12345
clients = []
s = socket(AF_INET, SOCK_DGRAM)
s.bind((host, port))
'#Set Blocking to 0 so it will accept basically everything'
s.setblocking(0)
quitting = False
print "server started....."
while not quitting:
try:
'#Receive 1024 bytes of data... Its basically 1KB :P '
data, addr = s.recvfrom(1024)
if "Quit" in str(data):
'#Quit if a specified string was detected...'
quitting = True
if addr not in clients:
'#If a new client was found, add them to the clients list'
clients.append(addr)
print time.ctime(time.time()) + str(addr) + ": :" + str(data)
for client in clients:
'#Send the data to all clients... This is a groupchat afterall :3'
s.sendto(data, client)
except:
'#Try again if something goes wrong.....'
pass
'#Close the connection when out of the loop'
s.close()
So any ideas? Thanks

Categories