I am writing server application in Python that listens for requests, processes them, and sends a response.
All req/resp are send from the same address and port to the server application. I need to recv/send messages simultaneously, and the server need to recieve/send messages from/to the same port and address. I found some tutorials for asynchore sockets, but there are only examples for TCP connections.
Unfortunately, I need UDP. When I change SOCK_STREAM to SOCK_DGRAM in the create method, I get an error.
return getattr(self._sock,name)(*args)
socket.error: [Errno 95] Operation not supported
I tried to use twisted, but I dont know how to write the sender part, which can bind to the same port as its listening. The last result was blocked port.
Is there any way how to use asyncore sockets with UDP or how to use twisted to send from the same port? Some examples will be higly appreciated.
You can pretty much just write the sending and receiving part of your code and they'll work together. Note that you can send and receive on a single listening UDP socket - you don't need one for each (particularly if you want to send from and receive on the same address).
from __future__ import print_function
from sys import stdout
from twisted.python.log import startLogging
from twisted.internet import reactor
from twisted.internet.protocol import DatagramProtocol
class SomeUDP(DatagramProtocol):
def datagramReceived(self, datagram, address):
print(u"Got a datagram of {} bytes.".format(len(datagram)))
def sendFoo(self, foo, ip, port):
self.transport.write(
(u"Foo datagram: {}".format(foo)).encode("utf-8"),
(ip, port))
class SomeSender(object):
def __init__(self, proto):
self.proto = proto
def start(self):
reactor.callLater(3, self._send)
def _send(self):
self.proto.sendFoo(u"Hello or whatever", b"127.0.0.1", 12345)
self.start()
startLogging(stdout)
proto = SomeUDP()
reactor.listenUDP(12345, proto)
SomeSender(proto).start()
reactor.run()
Related
I want to use socket to implement that the client/server can send and receive the files from each other. The client can send and receive the files from the server and vice versa for the server. Also, need to use the Tkinter module to complete the server and client GUI.
When the 2 GUIs are initialed, a thread is started to listen to the connection from the opposite end. That means the server has a thread for listening and accepting the connection from the client while receiving the file from the client, and at the client-side, the thread is used to listen and accept the connection from the server.
My confusion is that whether do I need 2 ports, one is used for sending file from the client to the server, another one is to receiving the files from the server? And do I need to create 2 sockets for sending and receiving files?
My current solution is using 2 ports and 2 sockets in the client-side. when sending the file, the client-side acts the client, while receiving file it acts the server. Correct?
To be brief, is it possible to use the same network socket simultaneously for listen and connect to with the same port? Or must I have two separate sockets, and if so, must the separate sockets also be bound to separate network ports?
Here is a simplified code that explains my questions. Any advice/comments are appreciated. Thanks.
class client():
def __init__(self):
self.clientTcpSock = None
self.initUI()
def initUI(self):
#create UI here
def createSocket(self):
s.clientTcpSock = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((HOST, PORT_1)) #PORT_1 download file port
s.listen(5)
self.clientTcpSock = s
def sendFile(self):
# !!! Here creates a new TCP socket, or can i still use the same clientTcpSock??
s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.connect((HOST, PORT_2)) # PORT_2 upload file port
s.send(b'hello world') # just for example
def receiveFile(self):
while True:
### receivefile here
self.clientTcpSock.close()
# call this function when init UI
def newTherad(self):
thread = threading.Thread(target=self.receiveFile, args=())
thread.setDaemon(True)
thread.start()
I may send messages to server from twisted client by calling connector.connect(). But clients will be made on different ports. Following code is demonstrated this case:
SERVER_HOST = 'localhost'
SERVER_PORT = '5000'
class EchoClient(protocol.Protocol):
def connectionMade(self):
self.transport.write("message")
self.transport.loseConnection()
class EchoFactory(protocol.ClientFactory):
def buildProtocol(self, addr):
print('Connected.')
return EchoClient()
def clientConnectionLost(self, connector, reason):
print('Lost connection. Reason:', reason)
connector.connect()
def main():
reactor.connectTCP(SERVER_HOST, SERVER_PORT, EchoFactory())
reactor.run()
And my twisted server say me:
Packet received, client 127.0.0.1:41930, size: 7
Connection lost
Packet received, client 127.0.0.1:41931, size: 7
Connection lost
Packet received, client 127.0.0.1:41932, size: 7
Connection lost
Packet received, client 127.0.0.1:41933, size: 7
Clients has different ports - 41930, 41931, etc. How send messages from twisted client with single port?
You can use the bindAddress parameter in either connectTCP, clientFromString, TCP4ClientEndpoint, or TCP6ClientEndpoint. Using your example, your code would look like:
reactor.connectTCP(SERVER_HOST, SERVER_PORT, EchoFactory(), bindAddress=('127.0.0.1',9999))
I would advise you to avoid this if it's not absolutely necessary because the port may be in use by another process and will cause an exception. It's better for the OS to chose the ip:port for your app to bind to.
I use Python 2.7.x (2.7.8) and am trying to write a program using twisted python to function like this:
Program waits for a messaged received through TCP 7001 or UDP 7000.
Messages received through UDP 7000 are bridged over to TCP 7001 going out.
I couldn't figure out how to bridge UDP to TCP, so I looked up an example on this site, like this one, Twisted UDP to TCP Bridge but the problem is that the example is lying because it doesn't work. I added a "print datagram" on datagramReceived to see if UDP responds to receiving anything at all and it does not. This is totally frustrating.
Here's my current test code altered a little bit from that example:
from twisted.internet.protocol import Protocol, Factory, DatagramProtocol
from twisted.internet import reactor
class TCPServer(Protocol):
def connectionMade(self):
self.port = reactor.listenUDP(7000, UDPServer(self))
def connectionLost(self, reason):
self.port.stopListening()
def dataReceived(self, data):
print "Server said:", data
class UDPServer(DatagramProtocol):
def __init__(self, stream):
self.stream = stream
def datagramReceived(self, datagram, address):
print datagram
self.stream.transport.write(datagram)
def main():
f = Factory()
f.protocol = TCPServer
reactor.listenTCP(7001, f)
reactor.run()
if __name__ == '__main__':
main()
As you can see I changed the ports to comply with my test environment and added a print datagram to see if anything calls datagramReceived. I have no problems sending TCP things to this program, TCPServer works just fine because dataReceived can be called.
I ran the code from your question (with one slight modification: I enabled logging). I used telnet to connect to the TCP server on port 7001. I used a Python REPL to create a UDP socket and send some datagrams to port 7000.
Here is my REPL transcript:
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> s.sendto('hello', ('127.0.0.1', 7000))
5
>>> s.sendto('world', ('127.0.0.1', 7000))
5
>>>
Here is my server log (formatted to fit on your screen):
... Log opened.
... Factory starting on 7001
... Starting factory <twisted.internet.protocol.Factory instance at 0x2b9b128>
... UDPServer starting on 7000
... Starting protocol <__main__.UDPServer instance at 0x2e8f8c0>
... hello
... world
And here's my telnet session transcript:
$ telnet localhost 7001
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
helloworld
My interpretation of these results is that the program actually works as specified. I wonder what you did differently when you tried it that produced different, non-working results.
What I would like to do is combine Twisted with the Cmd module in python's stdlib.
In short I would like to be able to get the bare-bones socket fd object from a connected Protocol to use as the stdin of the cmd.Cmd module in the stdlib.
In Long, My client that interfaces with my server uses the Cmd module to process commands and send those commands to the server.
On my server I would also like to use the same command processing method with the builting Cmd module. To do this i would need to specify the stdin and stdout of the command interpreter.
I could do this easily with the builtin sockets module, but i would like to do it with twisted if possible.
Here is some code to do what i want with plain sockets:
(Works with telnet)
# server
import socket
import cmd
class CmdProcessor(cmd.Cmd, object):
def __init__(self, sock, addr):
network = sock.makefile()
super(CmdProcessor, self).__init__(stdin=network, stdout=network)
self.sock = sock
self.addr = addr
# Run the cmd.Cmd processing loop
self.cmdloop()
def do_sayhi(self, args):
# When 'sayhi' is recieved over the socket,
self.sock.send("Hey yourself!")
def do_quit(self, args):
self.sock.close()
if __name__ == "__main__":
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.bind(("0.0.0.0", 2319))
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.listen(5)
sock, addr = server_sock.accept()
print("Connection accepted")
connection = CmdProcessor(sock, addr)
This is almost what i want to to do. I just typed this up quick so i may be missing somthing. Half of it works. Currently, if you telnet into the server like:
telnet 127.0.0.1 2319
And you send 'sayhi' nothing happens. But if you type 'sayhi' at the terminal you started the server from (There is a (Cmd) prompt) the output goes to the telnet client. So the stdout of the cmd.Cmd is working. But not the stdin. That probably has something to do with the fact that telnet sends CR-LF ('\r\n') by default. Where the cmd module may just listen for \n.
So how can get the fd or file object from a protocol in twisted to do what i am trying do achieve here with bare sockets?
And any insights on what the input from telnet connected to the server is not registering with the CmdProcessor?
Any advice, tips or pointers welcome. (Wait no, no pointers.)
Thanks.
I suggest that instead you might want to look at Manhole.
In general, the point of Twisted is not to use Python socket objects directly. That's a big part of Twisted's job. When you want to interact with the network using Twisted, you use Twisted's APIs instead - protocols and transports, if you're thinking about the lowest level.
You can add use_rawinput = False
class CmdProcessor(cmd.Cmd, object):
use_rawinput = False
def __init__(self, sock, addr):
....
This produces response for sayhi from telnet
How can I use HTTPServer (or some other class) to set up an HTTP server that listens to a filesystem socket instead of an actual network socket? By "filesystem socket" I mean sockets of the AF_UNIX type.
HTTPServer inherits from SocketServer.TCPServer, so I think it's fair to say that it isn't intended for that use-case, and even if you try to work around it, you may run into problems since you are kind of "abusing" it.
That being said, however, it would be possible per se to define a subclass of HTTPServer that creates and binds Unix sockets quite simply, as such:
class UnixHTTPServer(HTTPServer):
address_family = socket.AF_UNIX
def server_bind(self):
SocketServer.TCPServer.server_bind(self)
self.server_name = "foo"
self.server_port = 0
Then, just pass the path you want to bind to by the server_address argument to the constructor:
server = UnixHTTPServer("/tmp/http.socket", ...)
Again, though, I can't guarantee that it will actually work well. You may have to implement your own HTTP server instead.
I followed the example from #Dolda2000 above in Python 3.5 and ran into an issue with the HTTP handler falling over with an invalid client address. You don't have a client address with Unix sockets in the same way that you do with TCP, so the code below fakes it.
import socketserver
...
class UnixSocketHttpServer(socketserver.UnixStreamServer):
def get_request(self):
request, client_address = super(UnixSocketHttpServer, self).get_request()
return (request, ["local", 0])
...
server = UnixSocketHttpServer((sock_file), YourHttpHandler)
server.serve_forever()
With these changes, you can perform an HTTP request against the Unix socket with tools such as cURL.
curl --unix-socket /run/test.sock http:/test
Overview
In case it help anyone else, I have created a complete example (made for Python 3.8) based on Roger Lucas's example:
Server
import socketserver
from http.server import BaseHTTPRequestHandler
class myHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(b"Hello world!")
return
class UnixSocketHttpServer(socketserver.UnixStreamServer):
def get_request(self):
request, client_address = super(UnixSocketHttpServer, self).get_request()
return (request, ["local", 0])
server = UnixSocketHttpServer(("/tmp/http.socket"), myHandler)
server.serve_forever()
This will listen on the unix socket and respond with "Hello World!" for all GET requests.
Client Request
You can send a request with:
curl --unix-socket /tmp/http.socket http://any_path/abc/123
Troubleshooting
If you run into this error:
OSError: [Errno 98] Address already in use
Then delete the socket file:
rm /tmp/http.socket