First of all, at least with what you show, you have not implemented a method to exit the infinite cycle correctly and close both the socket and the file correctly. You can use the event Ctrl + C for example to close the server securely. You can watch Capture KeyboardInterrupt .
Regarding your error, you open your file in text mode ( "w+"
) but you try to write bytes in it. The error in particular is because when you make recibido + '\n'
you are trying to concatenate bytes ( recibido
) with a string str
and therefore with encoding "utf-8" ( '\n'
).
Either you decode the string you receive before passing it to write
:
import socket
import signal
import sys
file = open("mensajes.txt", "w+")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 5550))
s.listen(5)
def keyboard_interrupt(signal, frame):
file.close()
print ("Adios")
sc.close()
s.close()
sys.exit(0)
signal.signal(signal.SIGINT, keyboard_interrupt)
while True:
print("Servidor iniciado. Pulse 'Ctrl'+'c' para salir")
sc, addr = s.accept()
while True:
recibido = sc.recv(1024).decode("utf-8")
file.write(recibido + "\n")
print("Recibido: ", recibido)
nuestra_respuesta = input("Tu: ")
sc.send(nuestra_respuesta.encode('utf-8'))
Or open the file in binary mode:
import socket
import signal
import sys
file = open("mensajes.txt", "wb+")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 5550))
s.listen(5)
def keyboard_interrupt(signal, frame):
file.close()
print ("Adios")
sc.close()
s.close()
sys.exit(0)
signal.signal(signal.SIGINT, keyboard_interrupt)
while True:
print("Servidor iniciado. Pulse 'Ctrl'+'c' para salir")
sc, addr = s.accept()
while True:
recibido = sc.recv(1024)
file.write(recibido + b'\n')
print("Recibido: ", recibido.decode("utf-8"))
nuestra_respuesta = input("Tu: ")
sc.send(nuestra_respuesta.encode('utf-8'))
The line print("Recibido: ", recibido,"utf-8".decode("ascii"))
is not valid in Python 3. I do not know what you want with "utf-8".decode("ascii")
but str
(string "utf-8" in Python 3) does not have the method decode
as is logical, another thing is that Python 2 will be used.