962
Comment: fixed
|
1375
added client example
|
Deletions are marked like this. | Additions are marked like this. |
Line 5: | Line 5: |
== Sending == | See also: UdpCommunication |
Line 7: | Line 7: |
(to be written) | == Client == |
Line 9: | Line 9: |
== Receiving == | Here's simple code to send and receive data by TCP in Python: {{{ #!python #!/usr/bin/env python import socket TCP_IP = '127.0.0.1' TCP_PORT = 5005 BUFFER_SIZE = 1024 MESSAGE="Hello, World!" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) s.send(MESSAGE) data = s.recv(BUFFER_SIZE) s.close() print "received data:", data }}} == Server == |
Line 22: | Line 46: |
BUFFER_SIZE = 10 # Normally 1024, but we want fast response | |
Line 30: | Line 55: |
data = conn.recv(10) # buffer size is 10 bytes | data = conn.recv(BUFFER_SIZE) |
Line 37: | Line 62: |
---- | == Links == |
Line 39: | Line 64: |
See also: UdpCommunication Links: |
TCP Communication
See also: UdpCommunication
Client
Here's simple code to send and receive data by TCP in Python:
1 #!/usr/bin/env python
2
3 import socket
4
5
6 TCP_IP = '127.0.0.1'
7 TCP_PORT = 5005
8 BUFFER_SIZE = 1024
9 MESSAGE="Hello, World!"
10
11 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
12 s.connect((TCP_IP, TCP_PORT))
13 s.send(MESSAGE)
14 data = s.recv(BUFFER_SIZE)
15 s.close()
16
17 print "received data:", data
Server
Here's simple code to serve TCP in Python:
1 #!/usr/bin/env python
2
3 import socket
4
5
6 TCP_IP = '127.0.0.1'
7 TCP_PORT = 5005
8 BUFFER_SIZE = 10 # Normally 1024, but we want fast response
9
10 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
11 s.bind((TCP_IP, TCP_PORT))
12 s.listen(1)
13
14 conn, addr = s.accept()
15 print 'Connection address:', addr
16 while 1:
17 data = conn.recv(BUFFER_SIZE)
18 if not data: break
19 print "received data:", data
20 conn.send(data) # echo
21 conn.close()
Links
[http://www.python.org/doc/current/lib/module-socket.html socket] -- builtin Python module
[http://www.python.org/doc/current/lib/module-telnetlib.html telnetlib] -- builtin Python module
[http://woozle.org/~neale/papers/sockets.html Introduction to TCP Sockets] -- uses Python to explain
Discussion
- (none yet!)