Send message to localhost using XMPP in python - python

I have created a program to send chat messages via socket between two ports in localhost.
I need a third client who uses xmpp protocol to connect to localhost and sent message to here.When i run my server in terminal it shows this third client as connected
My code is given below:
import xmpp
msg='how r u :)'
client = xmpp.Client('localhost')
print "clienttttttttttttttttttt",client
con=client.connect(server=('localhost',5000))
#client.auth(username, passwd, 'botty')
#client.sendInitPresence()
message = xmpp.Message('localhost', msg)
print "messageeeeeeeeeeeeeeeeeeee",message
message.setAttr('type', 'chat')
client.send(message)
when i execute this code this error occurs
Registering protocol "error" as <class 'xmpp.protocol.Protocol'>(http://etherx.jabber.org/streams)
DEBUG: socket sent <?xml version='1.0'?>
<stream:stream xmlns="jabber:client" to="localhost" version="1.0" xmlns:stream="http://etherx.jabber.org/streams" >
Am using python xmpppy library.What is the issue here.How will i send my message to localhost which uses socket to send messages.Please help????

Related

Should data be sent all at once, or one by one in the WHOIS protocol?

Should data be sent all at once, or one by one in the WHOIS protocol?
So, when I create a whois server, should I do this:
Client sends "example.tld" to server
Server sends "Some info about example.tld" to the client
Server sends "Some more info about example.tld" to the client
Server sends "Remaining info about example.tld" to the client
CONNECTION CLOSED
OR:
Client sends "example.tld" to server
Server sends "All info about example.tld at once" to the client
CONNECTION CLOSED
So for Python, should I do socket.send(bytes("info about that domain requested\r\n", encoding="UTF-8")) for each line? Or should I do it for all of the lines at once, i.e., socket.send(bytes("all info about that domain\r\nthat was requested", encoding="UTF-8"))

One way web socket communication?

I was reading about the Python websocket-client library and realized that, to receive data, we have to start a connection:
from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
print "Received " + ws.recv() + "..."
What if I just need a one-way connection? Say a Python script is running on my laptop, and it periodically sends messages to a local web server.
To receive messages, the web server would have to start a connection, but starting a connection requires a URL to connect to. My Python script is not a web server, so it lacks a URL. How could the web server receive messages from the script?
I tried to let the server listen for clients to connect with it via
ws = websocket.WebSocket()
while 1:
print 'received "' + ws.recv()
However, I get an error.
in _recv
bytes = self.io_sock.recv(bufsize)
error: [Errno 107] Transport endpoint is not connected
That error output leads me to believe that the server needs to connect in order to receive.
If you would want one way connection to the server, you could just listen on plain socket or use UDP or use HTTP requests ore any other TCP protocol.

python SMTP - socket error

I have a python script to run a SMTP server in localhost. This is my very simple code:
import smtpd
import asyncore
class CustomSMTPServer (smtpd.SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
print 'Receiving message from:', peer
print 'Message addressed from:', mailfrom
print 'Message addressed to :', rcpttos
print 'Message length :', len(data)
server = CustomSMTPServer(('127.0.0.1', 25), None)
asyncore.loop()
If I send an email from an email client running on localhost the email arrives successfully in the STMP server. However, if I send an email from an email client running in a computer located in the same local network (192.168.1.1/24), it doesn't succeed. Here below the error I get from Outlook Express:
The connection to the server has failed. Account 'localhost', Server '192.168.1.115'.
Protocol SMTP, Port: 25, Secure(SSL): No, Socket Error: 10061, Error Number: 0x800CCC0E
Just in case, I deactivated McAfee firewall in both PCs but I still get the same error.
Where can be the problem? Does it have anything to do with the asyncore.loop() method? Thanks!
Your server is running on the loopback interface:
server = CustomSMTPServer(('127.0.0.1', 25), None)
That interface is not reachable from any external network, only from the local machine.
You will need to start your email server on a real network interface (such as 192.168.1.115, based on the error message).
Also, I doubt you'll be able to retrieve any message anyway. You are running an SMTP server: it accepts messages over SMTP but will not provided POP3 / IMAP services, so you can't retrieve messages using a remote email client. The SMTP server can be used to store messages in a local file-based message store though (and en email client running on the same machine could retrieve messages from the file, if correctly formatted).

How do multiple clients communicate using messaging system? (Python)

I have a server listening to all the clients that are connected to it, and each client should have this "username" they are identified by, but I'm stuck here... when a client wants to send a message to another client, they send the other client's username as the first word in the message sent to the server. Then I wouldn't know how to direct the message to the right socket (the receiving client). How should I link a client to its socket?? so I can call socket.send??
I'm currently modifying the code from this website: http://www.binarytides.com/code-chat-application-server-client-sockets-python/
Thanks!
def broadcast_data (sock, message):
#Do not send the message to master socket and the client who has send us the message
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
socket.close()
CONNECTION_LIST.remove(socket)
This function could be used as a starting point for a send function
def send_data (sock, message):
#send message to only one client
#sock is the socket of the client to send to
try :
sock.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
sock.close()
CONNECTION_LIST.remove(socket)
then you could have a dictionary of sockets associating them with a user name
usernameSockets={}
usernameSockets[username]=socket_for_user_name
then you could call the send_data function like
send_data(usernameSockets[username],message)
In the code you linked to there is no method for getting a username so you would have to have the clients send their username to the server when they are connecting to be able to populate a dictionary like the one I have mentioned above.

Formatting messages to send to socket.io node.js server from python client

I'm trying to get a Python client talking to a Node.js server using Socket.io 0.7, by sending a custom event to the server.
Based on the Socket.io reference I have found on GitHub, and the following WebSocket Python library.
Here's is my code so far:
Node server
io.sockets.on('connection', function (socket) {
socket.on('newimg', function(data) {
console.log(data);
});
});
Python client
def handshake(host, port):
u = urlopen("http://%s:%d/socket.io/1/" % (host, port))
if u.getcode() == 200:
response = u.readline()
(sid, hbtimeout, ctimeout, supported) = response.split(":")
supportedlist = supported.split(",")
if "websocket" in supportedlist:
return (sid, hbtimeout, ctimeout)
else:
raise TransportException()
else:
raise InvalidResponseException()
try:
(sid, hbtimeout, ctimeout) = handshake(HOSTNAME, PORT) #handshaking according to socket.io spec.
Except Exception as e:
print e
sys.exit(1)
ws = websocket.create_connection("ws://%s:%d/socket.io/1/websocket/%s" % (HOSTNAME, PORT, sid))
print ws.recv()
ws.send("2::")
ws.send("5:1::{'name':'newimg', 'args':'bla'}")
print ws.recv()
print "Closing connection"
ws.close()
Node console output
debug - client authorized
info - handshake authorized 12738935571241622933
debug - setting request GET /socket.io/1/websocket/12738935571241622933
debug - set heartbeat interval for client 12738935571241622933
debug - client authorized for
debug - websocket writing 1::
debug - websocket received data packet 2::
debug - got heartbeat packet
debug - websocket received data packet 5:1::{'name':'newimg', 'args':'bla'}
debug - acknowledging packet automatically
debug - websocket writing 6:::1
info - transport end
debug - set close timeout for client 12738935571241622933
debug - cleared close timeout for client 12738935571241622933
debug - cleared heartbeat interval for client 12738935571241622933
debug - discarding transport
Python console output
Done
1::
6:::1
Closing connection
Now it seems the socket event is not being triggered, despite the server responding with ACK. So the message is being correctly received but I am assuming, not formatted properly for socket.io to trigger an event.
I didn't think framing was necessary, however Archie1986 seems to disagree on his response to this: Socket.IO Client Library in Python
What might I be doing wrong here?
I wrapped rod's research into a barebones socket.io client library.
pip install -U socketIO-client
python
from socketIO_client import SocketIO
with SocketIO('localhost', 8000) as socketIO:
socketIO.emit('aaa')
socketIO.wait(seconds=1)
Resolved. I needed to use double quotes. Single quotes are not valid JSON. Woops.
ws.send("5:1::{'name':'newimg', 'args':'bla'}")
Becomes:
ws.send('5:1::{"name":"newimg", "args":"bla"}')

Categories

Resources