Limit number of users in a chatroom with a Twisted-based socket - python

I followed the following tutorial (http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server) and I got the code you can see below. This code allows an unlimited number of clients to connect to a chat. What I want to do is to limit this number of clients so that no more than two users can chat at the same chatroom.
In order to do so, I actually just need to know one thing: how to get a unique identifier for every client. Which can be used later on, in the function for c in self.factory.clients: c.message(msg) in order to only send the message to the client I want.
I'd appreciate any contribution!
# Import from Twisted
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
# IphoneChat: our own protocol
class IphoneChat(Protocol):
def connectionMade(self):
self.factory.clients.append(self)
print "Clients are ", self.factory.clients
def connectionLost(self, reason):
self.factory.clients.remove(self)
def dataReceived(self, data):
a = data.split(':')
print a
if len(a) > 1:
command = a[0]
content = a[1]
msg = ""
if command == "iam":
self.name = content
elif command == "msg":
msg = self.name + ": " + content
for c in self.factory.clients:
c.message(msg)
def message(self, message):
self.transport.write(message + '\n')
# Factory: handles all the socket connections
factory = Factory()
factory.clients = []
factory.protocol = IphoneChat
# Reactor: listens to factory
reactor.listenTCP(80, factory)
print "Iphone Chat server started"
reactor.run();

Try this: in connectionMade, if number of clients is already 2, close the new connection:
if len(self.factory.clients) == 2:
self.transport.loseConnection()

Related

Swift NSSocket programming/python tutorial fix

I know next to nothing about Python but I am trying to follow a tutorial on NSSockets in swift; and that uses python. This is the python script. Script was in python2, but I have to run it under python 3.
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
class IphoneChat(Protocol):
def connectionMade(self):
self.factory.clients.append(self)
print("clients are ", self.factory.clients)
def connectionLost(self, reason):
self.factory.clients.remove(self)
def dataReceived(self, data):
a = data.split(':')
print(a)
if len(a) > 1:
command = a[0]
content = a[1]
msg = ""
if command == "iam":
self.name = content
msg = self.name + " has joined"
elif command == "msg":
msg = self.name + ": " + content
print(msg)
for c in self.factory.clients:
c.message(msg)
def message(self, message):
self.transport.write(message + '\n')
factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(80, factory)
print("Iphone Chat server started")
reactor.run()
It works, but when I try and connect with my Swift code it sort of crashes with this message.
File "server.py", line 13, in dataReceived
a = data.split(':')
builtins.TypeError: a bytes-like object is required, not 'str'
Complaining that the data I am sending it is in the wrong format; this is the swift code that sends the message.
func sayhello() {
let response = String(format:"iam:brian")
let dataToSend = [UInt8](response.utf8)
outputStream?.write(dataToSend, maxLength: dataToSend.count)
}
How can I fix either the swift or the python? The tutorial I am trying to follow/translate is in.
https://www.raywenderlich.com/3932/networking-tutorial-for-ios-how-to-create-a-socket-based-iphone-app-and-server
Thanks to https://stackoverflow.com/users/1076479/gil-hamilton link I managed to work out what I am looking at. The solution. I am using the same swift code I posted here and I deleted the last section of the python. I am sending and receiving this.
Iphone Chat server started
clients are [<__main__.IphoneChat object at 0x1035039e8>]
b'iam:brian'
Now I know where the issue lies, with the python I can find the answer! I basically deleted this in the python script.
def dataReceived(self, data):
a = data.split(':')
print(a)
if len(a) > 1:
command = a[0]
content = a[1]
msg = ""
if command == "iam":
self.name = content
msg = self.name + " has joined"
elif command == "msg":
msg = self.name + ": " + content
print(msg)
for c in self.factory.clients:
c.message(msg)
def message(self, message):
self.transport.write(message + '\n')
And replaced it with this ...
def dataReceived(self, data):
print(data)
dumb=data.decode('utf8')
print(dumb)
Its so easy its stupid ....

Python: SocketServer has no socket

I want to use a Python socketserver to wait for a message, but to time out periodically and do some other processing. As far as I can tell, the following code should work, but the call to handle_request() throws an AttributeError exception, complaining that MyTCPServer object has no attribute 'socket'. What am I doing wrong?
import socketserver
class SingleTCPHandler(socketserver.BaseRequestHandler):
# One instance per connection. Override handle(self) to customize action.
def handle(self):
# self.request is the client connection
data = self.request.recv(1024) # clip input at 1Kb
print ("Received data: " + data.decode())
self.request.close()
class MyTCPServer(socketserver.BaseServer):
def __init__(self, serverAddress, handler):
super().__init__(serverAddress, handler)
def handle_timeout(self):
print ("No message received in {0} seconds".format(self.timeout))
if __name__ == "__main__":
print ("SocketServerWithTimeout.py")
tcpServer = MyTCPServer(("127.0.0.1", 5006), SingleTCPHandler)
tcpServer.timeout = 5
loopCount = 0
while loopCount < 5:
tcpServer.handle_request()
print ("Back from handle_request")
loopCount = loopCount + 1
socketserver.BaseServer is a common base class for both UDP and TCP servers.
Your code will work if your server inherits instead from socketserver.TCPServer.

Python - Twisted and PyAudio + Chat

I've been playing around with the Twisted extension and have fooled around with a chat room sort of system. However I want to expand upon it. As of now it only support multi-client chats with usernames ect. But I want to try and use the pyAudio extension to build a sort of VoIP application. I have a clientFactory and a simple echo protocol in the client and a serverFactory and protocol on the server. but I'm not entirely sure how to build off of this. What would be the best way to go about doing something like this?
Code to help if you need it
client.py:
import wx
from twisted.internet import wxreactor
wxreactor.install()
# import twisted reactor
import sys
from twisted.internet import reactor, protocol, task
from twisted.protocols import basic
class ChatFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent=None, title="WhiteNOISE")
self.protocol = None # twisted Protocol
sizer = wx.BoxSizer(wx.VERTICAL)
self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY)
self.ctrl = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER, size=(300, 25))
sizer.Add(self.text, 5, wx.EXPAND)
sizer.Add(self.ctrl, 0, wx.EXPAND)
self.SetSizer(sizer)
self.ctrl.Bind(wx.EVT_TEXT_ENTER, self.send)
def send(self, evt):
self.protocol.sendLine(str(self.ctrl.GetValue()))
self.ctrl.SetValue("")
class DataForwardingProtocol(basic.LineReceiver):
def __init__(self):
self.output = None
def dataReceived(self, data):
gui = self.factory.gui
gui.protocol = self
if gui:
val = gui.text.GetValue()
gui.text.SetValue(val + data)
gui.text.SetInsertionPointEnd()
def connectionMade(self):
self.output = self.factory.gui.text # redirect Twisted's output
class ChatFactory(protocol.ClientFactory):
def __init__(self, gui):
self.gui = gui
self.protocol = DataForwardingProtocol
def clientConnectionLost(self, transport, reason):
reactor.stop()
def clientConnectionFailed(self, transport, reason):
reactor.stop()
if __name__ == '__main__':
app = wx.App(False)
frame = ChatFrame()
frame.Show()
reactor.registerWxApp(app)
reactor.connectTCP("192.168.1.115", 5001, ChatFactory(frame))
reactor.run()
server.py:
from twisted.internet import reactor, protocol
from twisted.protocols import basic
import time
def t():
return "["+ time.strftime("%H:%M:%S") +"] "
class EchoProtocol(basic.LineReceiver):
name = "Unnamed"
def connectionMade(self):
#on client connection made
self.sendLine("WhiteNOISE")
self.sendLine("Enter A Username Below...")
self.sendLine("")
self.count = 0
self.factory.clients.append(self)
print t() + "+ Connection from: "+ self.transport.getPeer().host
def connectionLost(self, reason):
#on client connection lost
self.sendMsg("- %s left." % self.name)
print t() + "- Connection lost: "+ self.name
self.factory.clients.remove(self)
def lineReceived(self, line):
#actions to do on message recive
if line == '/quit':
#close client connection
self.sendLine("Goodbye.")
self.transport.loseConnection()
return
elif line == "/userlist":
#send user list to single client, the one who requested it
self.chatters()
return
elif line.startswith("/me"):
#send an action formatted message
self.sendLine("**" + self.name + ": " + line.replace("/me",""))
return
elif line == "/?":
self.sendLine("Commands: /? /me /userlist /quit")
return
if not self.count:
self.username(line)
else:
self.sendMsg(self.name +": " + line)
def username(self, line):
#check if username already in use
for x in self.factory.clients:
if x.name == line:
self.sendLine("This username is taken; please choose another")
return
self.name = line
self.chatters()
self.sendLine("You have been connected!")
self.sendLine("")
self.count += 1
self.sendMsg("+ %s joined." % self.name)
print '%s~ %s connected as: %s' % (t(), self.transport.getPeer().host, self.name)
def chatters(self):
x = len(self.factory.clients) - 1
s = 'is' if x == 1 else 'are'
p = 'person' if x == 1 else 'people'
self.sendLine("There %s %i other %s connected:" % (s, x, p) )
for client in self.factory.clients:
if client is not self:
self.sendLine(client.name)
self.sendLine("")
def sendMsg(self, message):
#send message to all clients
for client in self.factory.clients:
client.sendLine(t() + message)
class EchoServerFactory(protocol.ServerFactory):
protocol = EchoProtocol
clients = []
if __name__ == "__main__":
reactor.listenTCP(5001, EchoServerFactory())
reactor.run()
Take a look at Divmod Sine, a SIP application server. The basic idea is that you need an additional network server in your application that will support the VoIP parts of the application.

Python Twisted deferToThread function is not working as expected

My goal here is to make a simple server handling TCP message like "process My String" that send "My String" to be processed by a quite time taking operation called (here slowFunction). Here I'm calling this function through deferToThread but nothing seems to happened : the defered's callback messages doesn't show up anywhere (breakpoints show it's never called) and the print in the function aren't displayed (breakpoints show it's never called)
from twisted import protocols
from twisted.protocols import basic
from twisted.internet import threads, protocol, reactor
from twisted.application import service, internet
import re
import time
def slowFunction(arg):
print "starting process"
time.sleep(1)
print "processed "+arg
class MySimpleServer(basic.LineReceiver):
PROCESS_COMMAND = "process (.*)" #re pattern
processFunction = slowFunction
clients = []
def connectionMade(self):
print "Client connected"
MySimpleServer.clients.append(self)
def connectionLost(self, reason):
print "Client gone"
MySimpleServer.clients.remove(self)
def onProcessDone(self):
self.message("Process done")
def onError(self):
self.message("Process fail with error")
def lineReceived(self, line):
processArgumentResult = re.search(MySimpleServer.PROCESS_COMMAND, line)
if not processArgumentResult == None:
processArgument = processArgumentResult.groups()[0]
deferred = threads.deferToThread(MySimpleServer.processFunction, processArgument)
deferred.addCallback(self.onProcessDone)
deferred.addErrback(self.onError)
self.message("processing your request")
else:
print "Unknown message line: "+line
def message(self, message):
self.transport.write(message + '\n')
if __name__ == '__main__':
factory = protocol.ServerFactory()
factory.protocol = MySimpleServer
factory.client = []
reactor.listenTCP(8000, factory)
reactor.run()
I've got some help by the guys of twisted irc
The points are : the callback (onProcessDone and onError) are supposed to take a result argument, and the function called by deferToThread will receive self as an argument (it should one of the MySimpleServer class' method).
The final code is now :
from twisted import protocols
from twisted.protocols import basic
from twisted.internet import threads, protocol, reactor
from twisted.application import service, internet
import re
import time
def slowFunction(arg):
print "starting process"
time.sleep(20)
print "processed "+arg
class MySimpleServer(basic.LineReceiver):
PROCESS_COMMAND = "process (.*)" #re pattern
clients = []
def connectionMade(self):
print "Client connected"
MySimpleServer.clients.append(self)
def connectionLost(self, reason):
print "Client gone"
MySimpleServer.clients.remove(self)
def onProcessDone(self, result):
self.message("Process done")
def onError(self, result):
self.message("Process fail with error")
def processFunction(self, processArgument):
slowFunction(processArgument)
def lineReceived(self, line):
processArgumentResult = re.search(MySimpleServer.PROCESS_COMMAND, line)
if not processArgumentResult == None:
processArgument = processArgumentResult.groups()[0]
deferred = threads.deferToThread(self.processFunction, processArgument)
deferred.addCallback(self.onProcessDone)
deferred.addErrback(self.onError)
self.message("processing your request")
else:
print "Unknown message line: "+line
def message(self, message):
self.transport.write(message + '\n')
if __name__ == '__main__':
factory = protocol.ServerFactory()
factory.protocol = MySimpleServer
factory.client = []
reactor.listenTCP(8000, factory)
reactor.run()
Another way you could've done this is with staticmethod; this is the only legitimate use for it.
class MySimpleServer(basic.LineReceiver):
processFunction = staticmethod(slowFunction)

Python Twisted receive command from TCP write to Serial device return response

I've managed to connect to usb modem and a client can connect via tcp to my reactor.listenTCP,the data received from modem will be send back to client. I'm want to take dataReceived from client and send this to modem..I'm struggling to get this to work.Any help will be highly appreciated! the code:
from twisted.internet import win32eventreactor
win32eventreactor.install()
from twisted.internet import reactor
from twisted.internet.serialport import SerialPort
from twisted.internet.protocol import Protocol, Factory
from twisted.python import log
import sys
log.startLogging(sys.stdout)
client_list = []#TCP clients connecting to me
class USBClient(Protocol):
def connectionFailed(self):
print "Connection Failed:", self
reactor.stop()
def connectionMade(self):
print 'Connected to USB modem'
USBClient.sendLine(self, 'AT\r\n')
def dataReceived(self, data):
print "Data received", repr(data)
print "Data received! with %d bytes!" % len(data)
#check & perhaps modify response and return to client
for cli in client_list:
cli.notifyClient(data)
pass
def lineReceived(self, line):
print "Line received", repr(line)
def sendLine(self, cmd):
print cmd
self.transport.write(cmd + "\r\n")
def outReceived(self, data):
print "outReceived! with %d bytes!" % len(data)
self.data = self.data + data
class CommandRx(Protocol):
def connectionMade(self):
print 'Connection received from tcp..'
client_list.append(self)
def dataReceived(self, data):
print 'Command receive', repr(data)
#Build command, if ok, send to serial port
#????
def connectionLost(self, reason):
print 'Connection lost', reason
if self in client_list:
print "Removing " + str(self)
client_list.remove(self)
def notifyClient(self, data):
self.transport.write(data)
class CommandRxFactory(Factory):
protocol = CommandRx
def __init__(self):
client_list = []
if __name__ == '__main__':
reactor.listenTCP(8000, CommandRxFactory())
SerialPort(USBClient(), 'COM8', reactor, baudrate='19200')
reactor.run()
Your problem is not about twisted, but about python. Read this FAQ entry:
How do I make input on one connection result in output on another?
Thing is, if you want to send stuff to a TCP-connected client in your serial-connected protocol, just pass to the protocol a reference to the factory, so you can use that reference to make the bridge.
Here's some example code that roughly does this:
class USBClient(Protocol):
def __init__(self, network):
self.network = network
def dataReceived(self, data):
print "Data received", repr(data)
#check & perhaps modify response and return to client
self.network.notifyAll(data)
#...
class CommandRx(Protocol):
def connectionMade(self):
self.factory.client_list.append(self)
def connectionLost(self, reason):
if self in self.factory.client_list:
self.factory.client_list.remove(self)
class CommandRxFactory(Factory):
protocol = CommandRx
def __init__(self):
self.client_list = []
def notifyAll(self, data):
for cli in self.client_list:
cli.transport.write(data)
When initializing, pass the reference:
tcpfactory = CommandRxFactory()
reactor.listenTCP(8000, tcpfactory)
SerialPort(USBClient(tcpfactory), 'COM8', reactor, baudrate='19200')
reactor.run()
Thanks, got it to work.Could not get def notifyAll to send data to my modem..did it like this:for cli in client_list: cli.transport.write(data)
new code:
import sys
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.internet.protocol import Protocol
from twisted.internet.serialport import SerialPort
from twisted.python import log
log.startLogging(sys.stdout)
client_list = []#TCP clients connecting to me
usb_list = []
class USBClient(Protocol):
def __init__(self, network):
self.network = network
self.usb_list = []
def connectionFailed(self):
print "Connection Failed:", self
reactor.stop()
def connectionMade(self):
usb_list.append(self)
print 'Connected to USB modem'
USBClient.sendLine(self, 'AT\r\n')
def dataReceived(self, data):
print "Data received", repr(data)
print "Data received! with %d bytes!" % len(data)
for cli in client_list:
cli.transport.write(data)
#self.network.notifyAll(data)# !!AArgh..!Could not get this to work
pass
def lineReceived(self, line):
print "Line received", repr(line)
def sendLine(self, cmd):
print cmd
self.transport.write(cmd + "\r\n")
def outReceived(self, data):
print "outReceived! with %d bytes!" % len(data)
self.data = self.data + data
class CommandRx(Protocol):
def connectionMade(self):
print 'Connection received from tcp..'
client_list.append(self)
def dataReceived(self, data):
print 'Command receive', repr(data)
for usb in usb_list:
usb.transport.write(data)
def connectionLost(self, reason):
print 'Connection lost', reason
if self in client_list:
print "Removing " + str(self)
client_list.remove(self)
class CommandRxFactory(Factory):
protocol = CommandRx
def __init__(self):
self.client_list = []
def notifyAll(self, data):
for cli in self.client_list:
cli.transport.write('yipee')
if __name__ == '__main__':
tcpfactory = CommandRxFactory()
reactor.listenTCP(8000, tcpfactory)
SerialPort(USBClient(tcpfactory), '/dev/ttyUSB4', reactor, baudrate='19200')
reactor.run()

Categories

Resources