Broken Pipe with sockets in python

2

I'm having the following error whenever I try to send a message from the server to the client using sockets in Python:

server:

importsockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM)host='localhost'port=5008s.bind((host,port))s.listen(1)conn,addr=s.accept()whileTrue:data=conn.recv(1024).decode()print(data)msg=input("mensagem:")
    s.send(bytes(msg.encode()))

client:

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = 'localhost'
port = 5008
s.connect((host, port))
while True:
    msg = input("mensagem:")
    s.send(msg.encode())
    data = s.recv(1024).decode()
    print(data)
    
asked by anonymous 19.11.2016 / 20:09

1 answer

3

The most serious is this server-side line: s.send(bytes(msg.encode())) should be: conn.send(msg.encode('utf-8')) , and you are doing the encode / decode wrongly (from the beginning of python3.x), in this case you can even specify the char encoding that wants, in this case UTF-8, to do the following:

SERVER:

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('127.0.0.1', 9000))
    sock.listen(5)
    conn, addr = sock.accept()
    conn.send('WELCOME\n(isto veio do servidor)\n'.encode())
    while True:
        data = conn.recv(1024).decode()
        conn.send('(isto veio do servidor)... A sua menssagem foi: {}\n'.format(data).encode('utf-8'))

CLIENT:

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect(('127.0.0.1', 9000))
    while True:
        data = sock.recv(1024).decode()
        print(data)
        msg = input('messagem\n')
        sock.send(msg.encode())

NOTE: this is a server ready for a single client (socket, connection), if you want more connections your server will have to add parallelism (threading by ex) on the server side, so there is a process for each client

    
19.11.2016 / 20:30