Welcome to factor 2 of the sockets tutorial with Python. Within the former tutorial, we found how we might ship and acquire particulars utilizing sockets, however then we illustrated the difficulty that may come up when our communication exceeds our buffer measurement. On this tutorial, we’re going to chat about overcoming this!
Useful resource code and text-primarily based mostly tutorial: https://pythonprogramming.net/buffering-streaming-data-sockets-tutorial-python-3/
Channel membership: https://www.youtube.com/channel/UCfzlCWGWYyIQ0aLC5w48gBQ/sign up for
Discord: https://discord.gg/sentdex
Help the knowledge: https://pythonprogramming.web/assistance-donate/
Twitter: https://twitter.com/sentdex
Fb: https://www.fb.com/pythonprogramming.internet/
Twitch: https://www.twitch.tv set/sentdex
G+: https://in addition.google.com/+sentdex
#socket #networking #python
supply
How many coffee mug do you have man
Great video. The way how you implemented the method to get a message via header and msg length is not working however if new strings are sent every few milliseconds. On my second machine, it leads the msg to grow infinitely and never enter the == condition. This code fixed it for me if anyone has also use case with low latency applications. I simply receive only the header first because I know its length (in my case 10). Then I fetch exactly the msg length. Even if there is already a queue of strings in the socket waiting to be fetched, this method gets the messages reliably.
while True:
full_msg = '''
msglen = 0
new_msg = True
while True:
if new_msg:
msg = self.clientsocket.recv(10)
msglen = int(msg)
new_msg = False
else :
msg = self.clientsocket.recv(msglen)
#full_msg = msg.decode("utf-8")
#print(full_msg)
new_msg = True
actually its not one billion, its nine billion nine hundred and ninety nine million nine hundred and ninety nine thousand nine hundred and ninety nine…
4:36 this is how you laugh when you concatenate a variable to a formatted string instead of interpolating it
How many fancy cups do you have? Every single one is amazing!!
Extremely badly explained
What the heck is ":<"? Cant find it on google
Thank you for this tutorial , you have a great channel Machaa Allah ๐
Kinda bad at python, could anyone pls explain in the client code:
msg[:HEADERSIZE]
How does this give the message length? I tried printing a string in python from [ : i] where is just a random number and it just printed the beginning of a string up until i.
Wouldn't msg[:HEADERSIZE] only give the first 10 characters?
Love your teaching man
How you get that curly F?
can you create more vids about python sockets that is more complicated that you know hehe. u know ur expression great and u presentation too, nice video anyway continue posting python vids.
double while loop! dang!
Great videos as always, many thanks! It works perfectly fine if both server and client are on my local machine, but I'm not able to establish a connection between my local machine and a cloud hosted VM. Any idea how to make that work?
when running the client.py, on cmd its showing "new message length: b'22" nothing after it
you have some strange mags there
How would I send data to something other than the machine that the server is running on. For example how would one send data to other computers on the same wifi or even how could I send data to my friend who lives in another city?
new message length: b'22 ' -> what is that? I guess you missed the int() around the msg
Any chance I could get some feedback on this setup I've made?
I wrote a little socket-based library in hopes to make it easier to use, especially in LAN game use, or LAN chatrooms.
Here's a link to the github repo if anyone is interested :
https://github.com/Machine-builder/better-socket-system
MY Laptop hangs/freezes after sometimes, after connecting the server to the client and then the whole PC doesn't responses, then i have to directly put it off by forcing it to shutdown by the power button. why is it so??
When this guy stop laughing and jokeing around. I might learning something. Breaks my focus all the time!
CTRL + PAUSE BREAK will break you out of the program ๐ my 5 cents
How to send these messages to a bluetooth android receiver?
can someone explain me a little bit more about client.py code and msg[:HEADERSIZE] and msg[HEADERSIZE:] . How does it work?
I like you because you did not edit your run errors like others guys
Aren't we supposed to figure this out on our own?
I like this guy's positive attitude!
Hey wait so like how can you make the client / host both listen to data and wait for you to send data at the same time? like the threading module or what
how we can send some 20 Mb size of audio file from server to client …??
Awesome video! A bit of feedback, I think that it would help people if you explain more about how a socket works. It took me a while to figure out that sockets will close if there is no more data to be sent, which explains why you need buffering.
I did not know that you can CMD into a path like that. That was a bonus.
for some reason time only prints once to the screen then doesn't print again.
It's just simple code, but when they come together I don't get it anymore.
I keep getting the ValueError that says "invalid literal for int() with base 10: b' '
Question:
What is the purpose of all these nested loops, junk vars, conditions and string truncating? I replaced all 21 lines of your code with:
msg = s.recv(int(s.recv(HEADERSIZE)))
print(msg.decode("utf-8"))
Is there something necessary about your way? By observation, I am getting identical results, but I don't waste time looping baby chunks and juggling a bunch of extra code
—–
Also, what's up with:
msg = f'{len(msg):<{HEADERSIZE}}' + msg
Why not:
msg = f'{len(msg):<{HEADERSIZE}}{msg}'
and actually, why not:
def message(msg):
return f'{len(msg):<{HEADERSIZE}}{msg}'.encode('utf-8')
msg = message("Welcome to the server")
clientsocket.send(msg)
This way you have one function that formats all of your messages perfectly without you having to write the same thing repetitively? I know you would reply something like "This is only lesson 2. We will get to that point.", but isn't that why tutorials like these drag on forever? They get built up with a bunch of junk code that you have to replace and then you spend 2 or 3 tutorials undoing all the stuff that was written poorly. It doesn't take 2 loops, 3 vars and a condition to get a number and use it. Why not just write it to the most basic PROPER way the first time and build on that? The point of this tutorial was to create a header system, but you only did that half way (maybe not even that).
—–
"You can just embed more brackets inside of brackets"
EXCEPT if the opening bracket comes directly after another open bracket. "{{" is how you print 1 open bracket in an f-string.
example:
a, b = 10, 20
print(f'{{a} b}')
>>> '{a} b}'
It will treat the double open brackets as a single open bracket CHARACTER and fail to do any of what you expect.
You have the cooles coffee mugs ever!!!!
When getting massage from server i.e. in rcev() function you used ''int (msg[:HEADERSIZE]) " but I am getting error invalid literal for int() with base 10: how you are getting it correct , as when we use int() function on byte encoded stream it gives this error .
Is there something wrong with doing it this way? It doesn't close the connection, it also gets the whole message. Probably more effecient since it uses only one loop? I can put comments in code if someone needs it.
1)server.py
import socket
import time
buffersize = 10
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.bind( (socket.gethostname(), 1234) )
s.listen(5)
while True:
clientsocket, address = s.accept()
print( 'Connection with: ' + str(address) )
msg = 'Welcome to the server my friend!'
msg = f'{len(msg):^{buffersize}}' + msg
clientsocket.send( bytes(msg, 'utf-8') )
while True:
time.sleep(1)
mes = f'The time is: {time.time()}'
mes = f'{len(mes):^{buffersize}}' + mes
clientsocket.send( bytes(mes, 'utf-8') )
2) client.py
import socket
buffer_size = 10
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 1234))
full_msg = ''
new_msg = ''
x = 0
while True:
new_msg = s.recv(buffer_size).decode('utf-8')
full_msg += new_msg
if x == 0:
header = int(new_msg)
full_msg = ''
if len(full_msg) == header:
print(full_msg)
x = -1
x += 1
Really cool mugs tho
For anyone who wants a life pro-tip:
If you don't understand something done in a video, don't just copy it into the code. Actually skip it, or try to implement the code the way you think it should work. Usually you'll then see an issue, that's being resolved by the code in the video. Or be right, and your code will also work. Both are better than just copying something without understanding what is done. Happy coding!
Any idea how to do an equivalent of the f string f'{len(msg):<10}' in python 3.5 ?
The last line of code in the client.py file will never execute, so it can be deleted. That's line 28, print(full_msg). Also, I donโt think we need the first infinite loop in that file.
if you want to stop the server just do CTRL+C
great tutorial! helped me a bunch
I'm a little surprised this works consistently, with genuine Unicode data. I'd think that if, for whatever reason, a partial block of UTF-8 text were sent, that the the last character would be undecodable, and the next block would start with the remnants of an incomplete character encode. The assembly should be of bytes, and then at the very end, decode the bytes from utf-8.
can socket be used to send the results of video processing from python using opencv? like for object detection so you can access the video output from browser