Edit: There is a very reasonable reason that the term RTFM exists. Reading ... The manual is working. If I really read the manual, I would know that socket.accept () creates a client socket that will be used to communicate with the client. Apparently you should use this!
I am writing a simple chat program in Python using sockets. My code is still below (I am para-coding, the real thing is too long).
Class and import of servers:
import socket import os import socket from subprocess import Popen, PIPE import threading class Server: def __init__(self,name,port=5001): self.name = name self.port = port self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.bind(('',self.port)) self.server_listen() def server_listen(self): self.server_socket.listen(5) while 1: self.client, self.address = self.server_socket.accept() self.discourse() def discourse(self): DisplayMessages(self.server_socket).start()
I will omit the Client class as this is the same, except that it is related to:
self.client_socket.connect((self.host,self.port))
instead of accepting server-like connections. It sends input with the identical self.discourse method to the server. The DisplayMessage class is shown below. It starts as its own thread and an error occurs (only on the server, not on the client).
class DisplayMessages(threading.Thread): def __init__(self, socket): self.pipe = '/tmp/pyimPipe' if not os.path.exists(self.pipe): os.mkfifo(self.pipe) self.term = Popen(['xterm','-e','cat', self.pipe]) self.pipe_interface = open(self.pipe, 'w', 1) self.socket = socket threading.Thread.__init__(self) def run(self): self.display() def display(self): recv_bufr = '' while 1: recv_bufr = (recv_bufr + self.socket.recv(1024).decode('utf-8')) messages = recv_bufr.split('\n') recv_bufr = messages.pop() for line in messages: line = line.rstrip() if line.find('!dmsg') != -1: self.message(line) else: print("Alert: Broken Message Recieved") def message(self, line): message = line.split(':')[1:] if len(message) != 1: message = ':'.join(message) else: message = message[0] sender_name = message.split()[0] message = message.split()[1:] if len(message) != 1: message_text = '' for bit in message: message_text = message_text + ' ' + bit else: message_text = message[0] wrt_bufr = str(sender_name) + ':' + ' ' + message_text.strip() + '\n' self.pipe_interface.write(wrt_bufr) self.pipe_interface.flush() def alert(self): pass
The error in this line is:
recv_bufr = (recv_bufr + self.socket.recv(1024).decode('utf-8'))
but only when the server class uses the DisplayMessage class. I apologize for the length of this question. I wanted to publish too much code, not too little. Thank you