Python Networking responding wtih 'b' - python

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')

Related

Loop not occurring using python socket

I am using my server code on a raspberry pi and my client code on my laptop. I also off the firewall on my computer. After connecting to the server, I manage to run the loop for once from the client side by keying the word "data" and when I keyed in another command it just came out of the loop. If i key in Quit it says that it have an OS error98 address already in used. May I know how to keep the loop on going ? Below I is my client.py and server.py code.
Server.py code:
import socket
import numpy as np
import encodings
HOST = '192.168.1.65'
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
def random_data(): # ANY DATA YOU WANT TO SEND WRITE YOUR SENSOR CODE HERE
x1 = np.random.randint(0, 55, None) # Dummy temperature
y1 = np.random.randint(0, 45, None) # Dummy humidigy
my_sensor = "{},{}".format(x1,y1)
return my_sensor # return data seperated by comma
def my_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print("Server Started waiting for client to connect ")
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024).decode('utf-8')
if str(data) == "Data":
print("Ok Sending data ")
my_data = random_data()
x_encoded_data = my_data.encode('utf-8')
conn.sendall(x_encoded_data)
elif str(data) == "Quit":
print("shutting down server ")
break
else:
pass
if __name__ == '__main__':
while 1:
my_server()
Client.py Code:
import socket
import threading
import time
HOST = '192.168.1.65' # The server's hostname or IP address
PORT = 65432 # The port used by the server
def process_data_from_server(x):
x1, y1 = x.split(",")
return x1,y1
def my_client():
threading.Timer(11, my_client).start()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
my = input("Enter command ")
my_inp = my.encode('utf-8')
s.sendall(my_inp)
data = s.recv(1024).decode('utf-8')
x_temperature,y_humidity = process_data_from_server(data)
print("Temperature {}".format(x_temperature))
print("Humidity {}".format(y_humidity))
s.close()
time.sleep(5)
if __name__ == "__main__":
while 1:
my_client()
address already used
you need to use socket.setsockopt to set socket.SO_REUSEADDR in i think both client and server.py
def my_server():
# with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("Server Started waiting for client to connect ")
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024).decode('utf-8')
if str(data) == "Data":
...

Real time output whilst running Python

I'm making a basic chatroom and I want the received messages to show up when I'm also typing a message. I've looked it up, but from what I can tell it only works with a GUI, and I would prefer not to write a GUI.
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
str_return = ("")
str_send = ("blep")
old = ("blep")
port = input("Enter Port ")
try:
s.connect(("localhost", int(port)))
print("Connecting")
while True:
str_send = input("Enter message: ")
if str_send == ("exit"):
break
s.send(bytes(str_send, 'utf-8'))
str_recv = s.recv(1024)
print(str_recv.decode('utf-8'))
s.close()
except:
print("setting up server")
s.bind(('localhost', int(port)))
s.listen(5)
connect, addr = s.accept()
connect.sendto(bytes(str_return, 'utf-8'), addr)
print("Connection Address:" + str(addr))
while True:
str_send = input("Enter message: ")
if str_send == ("exit"):
break
connect.sendto(bytes(str_send, 'utf-8'), addr)
str_recv, temp = connect.recvfrom(1024)
print(str_recv.decode('utf-8'))
print("bye")
How can I make this work?

UDP TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

I'm completely newbie to python and computer networking. While working on Uni project I have faced a problem. What am I doing wrong? Any help will me much appreciated.
Here is server side:
import socket
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print ("Server Started.")
while True:
data, addr = s.recvfrom(1024)
print ("message from: ") + str(addr)
print ("from connected user: ") + str(data.decode('utf-8'))
data = str(data).upper()
print ("sending: ") + str(data)
s.sendto(data, addr)
s.close()
if __name__ == '__main__':
Main()
Here is my client side:
import socket
def Main():
host = "127.0.0.1"
port = 5000
server = ('127.0.0.1', 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
message = input('->')
while message != 'q':
s.sendto(message.encode('utf-8'), server)
data, addr = s.recvfrom(1024)
print ('Received from server: ') + str(data)
message = input('->')
s.close()
if __name__ == '__main__' :
Main()
There were a couple of issues; mostly with the printing.
You had a few instances of print('some text') + str(data); this won't work, because while print() outputs to the screen (STDOUT) it returns None, so what you were actually doing was trying to concatenate None + str(data)
What you need is print('some text' + str(data)).
Additionally, there was as issue on the server-side where you echo the data received from the client back to the client- it needed to be re-encoded as a bytearray (it comes in as a bytearray, gets converted to a utf-8 string for display, it needs to go back to bytearray before replying).
In summary, server:
import socket
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print("Server Started.")
while True:
try:
data, addr = s.recvfrom(1024)
print("message from: " + str(addr)) # moved string concatenation inside print method
print("from connected user: " + str(data.decode('utf-8'))) # moved string concatenation inside print method
data = str(data).upper()
print("sending: " + str(data)) # moved string concatenation inside print method
s.sendto(data.encode('utf-8'), addr) # needed to re-encode data into bytearray before sending
except KeyboardInterrupt: # added for clean CTRL + C exiting
print('Quitting')
break
s.close()
if __name__ == '__main__':
Main()
And the client:
import socket
def Main():
host = "127.0.0.1"
port = 5001
server = ('127.0.0.1', 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
message = input('->')
while message != 'q':
try:
s.sendto(message.encode('utf-8'), server)
data, addr = s.recvfrom(1024)
print('Received from server: ' + str(data)) # moved string concatenation inside print method
message = input('->')
except KeyboardInterrupt: # added for clean CTRL + C exiting
print('Quitting')
break
s.close()
if __name__ == '__main__':
Main()

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

audio over python tcp error

I am writing a simple python tcp code to send over a wav file however I seem to be getting stuck. can someone explain why my code is not working correctly?
Server Code
import socket, time
import scipy.io.wavfile
import numpy as np
def Main():
host = ''
port = 3333
MAX = 65535
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
print "Listening on port..." + str(port)
c, addr = s.accept()
print "Connection from: " + str(addr)
wavFile = np.array([],dtype='int16')
i = 0
while True:
data = c.recvfrom(MAX)
if not data:
break
# print ++i
# wavfile = np.append(wavfile,data)
print data
timestr = time.strftime("%y%m%d-%h%m%s")
print timestr
# wavF = open(timestr + ".wav", "rw+")
scipy.io.wavfile.write(timestr + ".wav",44100, data)
c.close()
if __name__ == '__main__':
Main()
Client Code
host, port = "", 3333
import sys , socket
import scipy.io.wavfile
# create a tcp/ip socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect the socket to the port where the server is listening
server_address = (host, port)
print >>sys.stderr, 'connecting to %s port %s' % server_address
input_data = scipy.io.wavfile.read('Voice 005.wav',)
audio = input_data[1]
sock.connect(server_address)
print 'have connected'
try:
# send data
sock.sendall(audio)
print "sent" + str(audio)
sock.close()
except:
print('something failed sending data')
finally:
print >>sys.stderr, 'closing socket'
print "done sending"
sock.close()
Please help someone, I want to send an audio file to my embedded device with tcp since it crucial data to be processed on the embedded device.
Not sure why you go to the trouble of using scipy and numpy for this, since you can just use the array module to create binary arrays that will hold the wave file. Can you adapt and use the simple client/server example below?
(Note: I've copy/pasted a small Windows sound file called 'tada.wav' to the same folder to use with the test scripts.)
Code for the server script:
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
print('Listening...')
conn, addr = s.accept()
print('Connected by', addr)
outfile = open("newfile.wav", 'ab')
while True:
data = conn.recv(1024)
if not data: break
outfile.write(data)
conn.close()
outfile.close()
print ("Completed.")
Code for the client:
from array import array
from os import stat
import socket
arr = array('B') # create binary array to hold the wave file
result = stat("tada.wav") # sample file is in the same folder
f = open("tada.wav", 'rb')
arr.fromfile(f, result.st_size) # using file size as the array length
print("Length of data: " + str(len(arr)))
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(arr)
print('Finished sending...')
s.close()
print('done.')
This works for me (though only tested by running both on localhost) and I end up with a second wave file that's an exact copy of the one sent by the client through the socket.

Categories