Broken Pipe with python sockets

Asked

Viewed 993 times

4

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

inserir a descrição da imagem aqui server:

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = 'localhost'
port = 5008
s.bind((host,port))
s.listen(1)
conn,addr = s.accept()
while True:
    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)
  • Post the code directly here, editing the question.

  • As requested I made Edit in the post including the code

1 answer

4


The most severe is this server side line: s.send(bytes(msg.encode())) must be: conn.send(msg.encode('utf-8')), and is doing wrong the Encounter/Code (birth of the prince who is with python3.x), in this case can even specify the char encoding which wishes, 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 single-client ready server (connection, socket), if you want more connections to your server you will need to add parallelism (threading for example) on the server side, so that there is a process for each client

  • thanks friend the same error was in s.send() and not in . Encounter() even so your help to point out the error was fundamental

Browser other questions tagged

You are not signed in. Login or sign up in order to post.