Server:
Import Socket Address
= (' 127.0.0.1 ', 31500)
s = socket.socket (socket.af_inet, socket. SOCK_DGRAM)
S.bind while
True:
data, addr = S.recvfrom (2048)
if not data:
print "Client" has exist "
break
print" Received: ", data," from ", addr
s.close ()
Client:
Import Socket Address
= (' 127.0.0.1 ', 31500)
s = socket.socket (socket.af_inet, socket. SOCK_DGRAM) while
True:
msg = raw_input ()
if isn't msg:
break
S.sendto (msg, address)
S.close ()
Run Result:
Server
[work@db-testing-com06-vm3.db01.baidu.com python]$ python udp_ss.py
Received:aaaaaa from (' 127.0.0.1 ', 10169)
received:123456 from (' 127.0.0.1 ', 10169)
Received:abcdef from (' 127.0.0.1 ', 10169)
Client
[work@db-testing-com06-vm3.db01.baidu.com python]$ python udp_cc.py
Aaaaaa
123456
ABCdef
[Work@db-testing-com06-vm3.db01.baidu.com python]$
Python is too convenient, too easy to use, the three-party library support and all, the syntax is simple, for developers, it is home travel, xxxx the necessary tool. The weekend looked at Python's network support and made a note for later browsing.
Python support BSD socket for network programming, its API and C, the same as the first look at the TCP mode, speaking of network programming, will certainly design to the server and client, respectively, to see
TCP Mode server side
The server-side socket general process is this:
Create a socket (you can choose the socket type Inet,unix and so on, as well as the connection mode TCP/UDP)
Use bind to expose a port so that the client can easily connect
Set the size of a listen queue
into an infinite loop, in this infinite loop, using the Accept function to wait for the client to connect, this function returns a new socket, corresponds to the client socket, establishes the communication channel. The processing of the socket is generally placed in an external separate function (concurrent)
Read and write to the socket via send ()/RECV ()