Решил написать клиент-серверный чат, почитал про сокеты и потоки. Нашел готовый код, который почти удовлетворяет моим требованиям по логике работы.
Сервер:
import socket, threading, string
debug = True
_connector = None
_running = True
_host = '127.0.0.1'
_port = 12345
_maxClient = 999
_recvBuffer = 2000
def printd (aString):
if debug:
print (aString)
class talkToClient (threading.Thread):
def __init__(self, clientSock, addr):
self.clientSock = clientSock
self.addr = addr
threading.Thread.__init__(self)
def run (self):
while True:
recvData = self.clientSock.recv (_recvBuffer)
if not recvData:
self.clientSock.send ('bye')
break
printd('Client ' + str (self.addr) + ' say "' + str (recvData) + '"')
for p in range(len(list)):
self.clientSock.sendto(recvData, list[p])
if recvData == "exit":
break
self.clientSock.close ()
_connector = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
_connector.bind ((str(_host), int(_port)))
_connector.listen (int(_maxClient))
list = []
while _running:
printd ('Running on ' + _host + ':' + str (_port) + '.')
channel, details = _connector.accept ()
list.append(details)
printd ('Conect on : ' + str (details))
talkToClient (channel, details).start ()
_connector.close ()
import socket, string
debug = True
_connector = None
_running = True
_host = '127.0.0.1'
_port = 12345
_recvBuffer = 2000
_connector = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
_connector.connect ((str(_host), int(_port)))
while _running:
sendData = input ("> ")
_connector.send (bytes(sendData,'utf-8'))
recvData = _connector.recv (_recvBuffer)
print (recvData)
if recvData == "bye":
break
if recvData == "exit":
break
_connector.close ()
list.append(details)
for p in range(len(list)):
self.clientSock.sendto(recvData, list[p])