[Tutor] Talking to UDPServer

Johan Geldenhuys johan at accesstel.co.za
Tue Nov 1 20:38:57 CET 2005


I've done some network programming mostly with TCP and I don't think 
that the way the client connects to the server is a lot different (if 
any), The only difference is when you must decide the protcol family. 
"socket.SOCK_DGRAM" will be for UDP and "socket.SOCK_STREAM" will be for 
TCP. After this, the client can connect the same way.

Here is a simpler sample than the one Kent gave:

"""
from socket import *

HOST = 'localhost'
PORT = 3001
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM) # change here for UDP
tcpCliSock.connect(ADDR)

while 1:
    data = raw_input('>') # Enter text to be transmitted to the server.
    if not data: break
    tcpClisock.send(data)
    data = tcpCliSock.recv(BUFSIZ)
    if not data: break
    print data
   
tcpCliSock.close()
"""
HTH,

Johan


Kent Johnson wrote:

> Carroll, Barry wrote:
>
>> Yes, that is exactly what I want.  I need to write a program that 
>> communicates with an existing server, using the UDP protocol.  This 
>> is my first time writing such a program, and I need help getting 
>> started. 
>
>
> Here is an example from Python Network Programming, by John Goerzen. 
> It opens a UDP port, sends a message, then echoes any received text to 
> the console. There is no higher-level support built in to Python, you 
> just open a datagram socket and push data out. Google for "Python udp" 
> for more examples.
>
> Kent
>
> #!/usr/bin/env python
> # UDP Example - Chapter 2
>
> import socket, sys, time
>
> host = sys.argv[1]
> textport = sys.argv[2]
>
> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> try:
>    port = int(textport)
> except ValueError:
>    # That didn't work.  Look it up instread.
>    port = socket.getservbyname(textport, 'udp')
>
> s.connect((host, port))
> print "Enter data to transmit: "
> data = sys.stdin.readline().strip()
> s.sendall(data)
> s.shutdown(1)
> print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
> while 1:
>    buf = s.recv(2048)
>    if not len(buf):
>        break
>    print "Received: %s" % buf
>
>


More information about the Tutor mailing list