Python 3.x Socket Module: "bytes like object not str" - python

I am in the process of making a simple networking messaging interface, using the Sockets module preinstalled in Python 3.5.1 . The code returns with a
TypeError: a bytes-like object is required, not 'str'
The server receives the message, but after that the program crashes with that error^I have done research and am aware of using .encode/.decode('utf-8') but it still returns the same error. The error is on the tcpServer.py file, whose source code will be below. I've read about using b'string here' but i don't know if it is applicable to variables. Thank you in advance.
Source:
import socket
def Main():
host = "127.0.0.1" #makes localhost the host server
port = 5000 #any random port between 1024 and 65535
s = socket.socket() #creates a new socket object
s.bind((host, port))
s.listen(1) #listens for 1 connection
c, addr = s.accept() #accepts a connection and address
print("Connection from: ", str(addr))
while True:
data = c.recv(1024) #receives bytes from connection with a 1024 buffer
if not data:
break
print("From Client: ",str(data.decode()))
data = str(data).upper() #overwrites current values in var data with a string of the new data in uppercase
print("Sending: ",str(data))
c.send(data) #tells connection to send the data
c.close()
if __name__ == "__main__":
Main()

Related

TCP connection with Python sockets - send() function issue

I am trying to establish TCP connection on the client-side using socket. The first part seem to work fine:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 1234 # The port used by the server
s.connect((HOST, PORT))
Now for the send() the server-side requires:
Once a client is connected it needs to send the following string in order to send a marker: <TRIGGER>XXXX</TRIGGER>In our case XXX is defined as var.trigger
When I write it like s.send(bytes (var.trigger)) it runs with no errors, however, I guess because it is not defined as a string the server does not recognize it.
Thank you in advance
p.s. I don't code in Python so it can be something very basic that I am missing here.
I am also fairly new to python sockets, but I tried this and it worked. My guess is that you need to wait for the data to be sent (on your server side) with something like this:
while True: # Infinite loop
data = conn.recv(1024) # 1024 = number of bytes to be recieves
if not data: # If data is false, or an empty string/list, etc.
break
print("Recieved:", data.decode('utf-8')) # Printing recieved data
The full code is as follows:
import socket
# ========== SERVER ==========
def server():
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) # Setting up socket
HOST = '127.0.0.1' # Localhost
PORT = 65432
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept() # Accepting connection
print("========== SERVER ==========")
print("Connected by:", addr)
while True: # Infinite loop
data = conn.recv(1024) # 1024 = number of bytes to be recieves
if not data: # If data is false, or an empty string/list, etc.
break
print("Recieved:", data.decode('utf-8')) # Printing recieved data
# ========== CLIENT ==========
def client():
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
HOST = '127.0.0.1' # Localhost
PORT = 65432
s.connect((HOST, PORT)) # Connecting to server
print("========== CLIENT ==========")
var = 'XXXX' # Replace with actual variable
s.sendall(f"<TRIGGER>{var}<TRIGGER>".encode('utf-8')) # Sending trigger message
print(f"Sent: <TRIGGER>{var}<TRIGGER>")

getting an error when try to pass the messege to client

sir, i am developing an server client appication using python. but when i run the server it just works fine and when i run the client, in the server i am getting an error saying
conn.sendall(reply)
TypeError: a bytes-like object is required, not 'tuple'
it seems like server cannot reply the messege to client. but i have no idea how to solve it. please anyone help me... here is my server code:
import socket
import sys
HOST = '127.0.0.1'; # Symbolic name meaning all available interfaces
PORT = 2014; # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket created")
print ("Socket bind complete")
s.bind((HOST, PORT))
s.listen(10)
print ("Socket now listening")
#now keep talking with the client
while True:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print ("Connected with ", addr[0] ,":" , str(addr[1]))
data = conn.recv(1024)
reply = ("O", data)
if not data:
break
conn.sendall(reply)// here it comes the error, i have used encode.('utf-8') but no luck
conn.close()
s.close()

TypeError: Can't convert 'builtin_function_or_method' object to str implicitly SOCKETS

I am have recently been learning about networking. So I tried doing an experiment I found on the web. It was a simple server client connection. But I got this error when I tried running my server.py:`
TypeError: Can't convert 'builtin_function_or_method' object to str implicitly
This is the code for server.py:
import socket # socket module
s = socket.socket() # creates socket object "s"
host = socket.gethostname # gets name of local pc
port = 5567 # Reserve a port for the service (numbers are random)
s.bind((host, port)) # connects our host and port number to our socket
s.listen(5) # waits for client connection (5 maximum connections)
while True: # repeats forever
c, addr = s.accept # Establishes connectd from anyone who tries to connect (c is client object)
print('Got connection from, '+ addr ) # prints on server gui its connection
c.send('Thank you for connecting!') # sends client message
c.close() # stops all connection to current client
The error was on line 6.
Thank you in advance.
You are forgetting to call your functions:
host = socket.gethostname # gets name of local pc
and
c, addr = s.accept # Establishes connectd from anyone who tries to connect (c is client object)
Both socket.gethostname and s.accept are callables, add ():
host = socket.gethostname()
and
c, addr = s.accept()
The exception you see is caused by you passing in the socket.gethostname function rather than what the function produces.

My simple client crash everytime it tries to connect to my python socket server

My client crash everytime it tries to connect to my python socket server. I dont know why but but my server seams to start up fine then when i start up my client it establishes a connection to the server but it crash direct. Im doing almost as what they say in py socket docs so im wondering if i have missed something or just staring blindly on something easy. Could any one help pls im using python3.4.
server.py
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes: break
print("Recieved: "+(databytes.decode('utf-8')))
response = input("Reply: ")
if response == "exit":
break
conn.sendall(response.encode('utf-8'))
conn.close()
client.py
import socket
host = '127.0.0.1'
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected to "+(host)+" on port "+str(port))
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
while True:
data = s.recv(1024)
print("Recieved: "+(data.decode('utf-8')))
response = input("Reply: ")
if response == "exit":
break
s.sendall(response.encode('utf-8'))
s.close()
There are two issues in your server/client programs.
You server has two accept() calls, before the while loop and inside the while loop , this causes the server to actually wait for two connections before it can start receiving any messages from any client.
The socket.sendall() function takes in bytes not string , so you need to encode the string using some suitable encoding to convert it to bytes , before sending the data . Also , the function - socket.recv() - returns bytes . So you need to decode the bytes data (using the same encoding you used to encode when sending) , so that you can get the correct string back and it can be printed. A suitable encoding can be - utf-8 - but you can use any encoding of you choice.
An example of encoding a string and using sendall() func -
s.sendall(response.encode('utf-8'))
an example of decoding the string when receiving the data -
databytes = conn.recv(1024)
if not databytes: break
data = databytes.decode('utf-8')
You do not neccessarily need to store the decoded value in another variable, you can also directly call the .decode('utf-8') function when printing the data like - print("Recieved: "+(data.decode('utf-8'))) .

python socket beginner error

I just started coding in python I can't the encryption part of strings
I am trying to run this simple server client code
(The client is to run on raspberry-pi)
server :
#!/usr/bin/env python
import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
BUFFER_SIZE = 24
conn, addr = server_socket.accept()
print ('Got connection from', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print ("received data:", data)
conn.send(data) # echo
conn.close()
Client:(were I have the error)
import socket
client_socket = socket.socket()
client_socket.connect(("192.168.1.4", 8000))
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
client_socket.send(MESSAGE)
data = client_socket.recv(BUFFER_SIZE)
client_socket.close()
print ("received data:", data)
The error here =:
File"c.py" line 9, in <module>
client_socket.send<MESSAGE>
typeError:'str' does not support the buffer interface
In python3 the interface to socket.send() changed to accept bytes instead of a string. See the difference between Python 3 docuentation and Python 2 documenation.
The solution is to encode the string before passing it to send() as follows:
client_socket.send(MESSAGE.encode())
In Python 3x strings are unicode, and they have to be encoded to bytes to send to a socket. The line:
client_socket.send(MESSAGE)
needs to be changed to:
client_socket.send(MESSAGE.encode('utf-8'))
On the server side you can decode data to get a string.

Categories

Resources