0

Lately, I have been developing this piece of code with my knowledge of networking in order to test it and see how it works.I was trying to interact with TCP servers. It goes like this:

from socket import *
bag = socket(AF_INET,SOCK_STREAM)
bag.bind(("",9000))
bag.listen(5)
while True:
    c,a = bag.accept()
    print ("Received connection from", a)
    c.send("Hello %s\n" % a[0])
c.close()

And the console printed this out:

Traceback (most recent call last): File "/Users/spathen/PycharmProjects/untitled31/jsyk.py", line 8, in Received connection from ('127.0.0.1', 50162) c.send("Hello %s\n" % a[0]) TypeError: a bytes-like object is required, not 'str'

Process finished with exit code 1

Any ideas on why this isn't working. An I not doing this right? Is there something going on? Do I have to send datagrams with UDP instead?

  • It seems like the error message is pretty self-explanatory. It requires a bytes-like object. Not a `str`. – juanpa.arrivillaga Jan 25 '17 at 00:50
  • Also, please edit your title to be more descriptive of the problem you are encountering. Received such and such error when trying to do such and such. – juanpa.arrivillaga Jan 25 '17 at 00:53
  • 2
    Possible duplicate of [TypeError: a bytes-like object is required, not 'str'](http://stackoverflow.com/questions/33003498/typeerror-a-bytes-like-object-is-required-not-str) – juanpa.arrivillaga Jan 25 '17 at 00:54
  • So would I have to interact with UDP servers in order to send datagrams –  Jan 25 '17 at 00:59
  • 1
    What? Is that suppose to be a response to something I asked? Again, you cannot `.send` a `str`. It has to be `bytes`. Look at the duplicate. – juanpa.arrivillaga Jan 25 '17 at 01:02
  • Yes, sorry I'm new to stack overflow. –  Jan 25 '17 at 01:04
  • The way I was sending data was through the TCP transport layer protocol, but since UDP transport layer protocols are a little bit different, do I send data with UDP instead. –  Jan 25 '17 at 01:07
  • 1
    I do not know how to be more clear. The error has nothing to do with the protocol, it is because you must use `bytes` instead of `str`. – juanpa.arrivillaga Jan 25 '17 at 01:10
  • Alright I'll send binary datagrams. –  Jan 25 '17 at 01:12
  • 1
    Do you understand the distinction between `bytes` and `str` types in Python? Because you seem to be completely misinterpreting what I am telling you. – juanpa.arrivillaga Jan 25 '17 at 01:14

0 Answers0