Imported Upstream version 3.2.2
[debian/gnuradio] / grc / grc_gnuradio / blks2 / tcp.py
1 #
2 # Copyright 2009 Free Software Foundation, Inc.
3 #
4 # This file is part of GNU Radio
5 #
6 # GNU Radio is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3, or (at your option)
9 # any later version.
10 #
11 # GNU Radio is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with GNU Radio; see the file COPYING.  If not, write to
18 # the Free Software Foundation, Inc., 51 Franklin Street,
19 # Boston, MA 02110-1301, USA.
20 #
21
22 from gnuradio import gr
23 import socket
24 import os
25
26 def _get_sock_fd(addr, port, server):
27         """
28         Get the file descriptor for the socket.
29         As a client, block on connect, dup the socket descriptor.
30         As a server, block on accept, dup the client descriptor.
31         @param addr the ip address string
32         @param port the tcp port number
33         @param server true for server mode, false for client mode
34         @return the file descriptor number
35         """
36         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
37         if server:
38                 sock.bind((addr, port))
39                 sock.listen(1)
40                 clientsock, address = sock.accept()
41                 return os.dup(clientsock.fileno())
42         else:
43                 sock.connect((addr, port))
44                 return os.dup(sock.fileno())
45
46 class tcp_source(gr.hier_block2):
47         def __init__(self, itemsize, addr, port, server=True):
48                 #init hier block
49                 gr.hier_block2.__init__(
50                         self, 'tcp_source',
51                         gr.io_signature(0, 0, 0),
52                         gr.io_signature(1, 1, itemsize),
53                 )
54                 fd = _get_sock_fd(addr, port, server)
55                 self.connect(gr.file_descriptor_source(itemsize, fd), self)
56
57 class tcp_sink(gr.hier_block2):
58         def __init__(self, itemsize, addr, port, server=False):
59                 #init hier block
60                 gr.hier_block2.__init__(
61                         self, 'tcp_sink',
62                         gr.io_signature(1, 1, itemsize),
63                         gr.io_signature(0, 0, 0),
64                 )
65                 fd = _get_sock_fd(addr, port, server)
66                 self.connect(self, gr.file_descriptor_sink(itemsize, fd))