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
Related
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.
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)
I have a socket project running. This is the base project and some features.
This is server file:
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, 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 = "192.168.43.67"
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()
I added HOST ip manually getting from ifconfig.
and client file is:
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import tkinter
def receive():
"""Handles receiving of messages."""
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
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.
my_msg.set("Type your messages here.")
scrollbar = tkinter.Scrollbar(messages_frame) # To navigate through past messages.
# Following will contain the messages.
msg_list = tkinter.Listbox(messages_frame, height=15, width=50, 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)
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: ')
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()
When i run server and send to my friend my ip I get from ifconfig he can't connect yo my server.
I am sending wrong ip?
- Firewall desactivated
I am trying to make a simple chat application using Python 3. I have seen this work in the past, where my client is able to connect to my server, and messages can be sent successfully. I want to move the app from a script working in the python idle shell to a GUI built with TKinter. Using entry and button widgets, a client can connect to the server for a fraction of a second, then is immediately disconnected. This only seems to happen because I am trying to use tkinter.
Error message is:
%$%$ has connected.
Exception in thread Thread-33:
Traceback (most recent call last):
File "C:\Users\lmaor\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\lmaor\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\lmaor\Desktop\Server 2.py", line 32, in handle_client
name = client.recv(BUFSIZ).decode("utf8")
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
The client-side code is:
#Importing packages
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import tkinter
from tkinter import *
from tkinter import messagebox
global client_socket
global HOST
global PORT
#These are here to stop the program breaking later on
HOST = 1
PORT = 1
BUFSIZ = 1024
client_socket = socket(AF_INET, SOCK_STREAM)
#This unsuccessfully connects to the server
def connect():
HOST = etyHost.get()
PORT = etyPort.get()
if not PORT:
PORT = 33000 # Default value.
else:
PORT = int(PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
#Creates a function to receive messages at any time
def receive():
while True:
try:
global client_socket
msg = client_socket.recv(BUFSIZ).decode("utf8")
msgChatlog.insert(END, msg)
except OSError:
break
#Creates a function to send messages
def send(event=None): #Event is passed by binders
msg = varMessage.get()
varMessage.set("") #Clears input field
client_socket.send(bytes(msg, "utf8"))
if msg == "{quit}":
client_socket.close()
top.quit()
#When closing window
def on_closing(event=None):
varMessage.set("{quit}")
send()
#Create tkinter window
jahchat = Tk()
jahchat.geometry("500x500")
jahchat.configure(background = "black")
jahchat.resizable(False, False)
jahchat.title("JahChat")
#
#Frame contains everything. useless
frmMessage = Frame()
#Var message is what goes into the chat
varMessage = StringVar() # For the messages to be sent.
varMessage.set("Type your messages here.")
#Scrollbar for the chatlog
srlChatlog = Scrollbar(frmMessage) # To navigate through past messages.
#
msgChatlog = Listbox(frmMessage, height=15, width=100, yscrollcommand=srlChatlog.set)
srlChatlog.pack(side=RIGHT, fill=Y)
msgChatlog.pack(side=LEFT, fill=BOTH)
msgChatlog.pack()
frmMessage.pack()
#
etyMessage= Entry(textvariable=varMessage)
etyMessage.bind("<Return>", send)
etyMessage.pack()
btnMessage = Button(text="Send", command=send)
btnMessage.pack()
#jahchat.protocol("WM_DELETE_WINDOW", on_closing)
#Entry box
etyHost = Entry(jahchat)
etyHost.pack()
etyHost.place(x = 0, y = 250)
#Entry box
etyPort = Entry(jahchat)
etyPort.pack()
etyPort.place(x = 0, y = 275)
#Button
btnConnect = Button(jahchat, text = "Connect", command = connect)
btnConnect.config(width = 20)
btnConnect.place(x = 0, y = 320)
#========================================================
#This is the code that sucessfully connects to the server
#HOST = input("host")
#PORT = input("port")
#if not PORT:
# PORT = 33000 # Default value.
#else:
# PORT = int(PORT)
#client_socket = socket(AF_INET, SOCK_STREAM)
#BUFSIZ = 1024
#ADDR = (HOST, PORT)
#print (ADDR)
#print (type(ADDR))
#client_socket.connect(ADDR)
#receive_thread = Thread(target=receive)
#receive_thread.start()
#===========================================================
jahchat.mainloop() # Starts GUI execution.
The server code is:
#Importing packages
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
#Sets up constant variables for later use
clients = {}
addresses = {}
HOST = '' #Client has to set this as their host to connect
PORT = 33000 #Client has to set this as their port to connect
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
#Creates a function that handles clients into the server
def accept_incoming_connections():
while True:
client, client_address = SERVER.accept()
print ("%$%$ has connected." .format(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()
#Takes client socket as argument.
def handle_client(client):
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, name+": ")
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s has left the chat." % name, "utf8"))
break
#Broadcasts message to whole server
def broadcast(msg, prefix=""): #Prefix is for name identification.
for sock in clients:
sock.send(bytes(prefix, "utf8")+msg)
def checkIP():
print (HOST, PORT, ADDR)
if __name__ == "__main__":
SERVER.listen(5) # Listens for 5 connections at max.
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start() #Starts the infinite loop.
ACCEPT_THREAD.join()
SERVER.close()
All answers appreciated.
I've just started python networking, and after looking at a few internet tutorials, I gave it a go... only problem is, whenever I get a response from the sever, it prints as in:
Recieved from: (Host & Port)b'Hey' - where I haven't put the b anywhere.
Here is the server code:
import socket
import tkinter
import time
import sys
def Main():
top = tkinter.Tk()
top.configure(background='black')
host = '10.0.0.2'
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
while True:
con = tkinter.Label(top, text="Connection from: " + str(addr), bg='red', fg='white').pack()
data = c.recv(1024)
if not data:
break
conn = tkinter.Label(top, text="Recieved from: " + str(addr) + str(data), bg='black', fg='white').pack()
top.mainloop()
c.close()
Main()
And my client:
import socket
def Main():
host = '10.0.0.2'
port = 5000
s = socket.socket()
s.connect((host, port))
message = input("> ")
while message != 'quit':
s.send(message.encode('ascii'))
message = input(">")
s.close()
Main()
Thanks for any input - I'm not really good at this yet! (My hosts aren't my computer so that's not the issue)
When you call socket.recv() in Python 3 it returns a bytes object, not a normal string. You can convert it to a normal string as follows:
data.decode('utf-8')