Implement socket communication (UDP) using Python)

Source: Internet
Author: User
ArticleDirectory
    • Server
    • Client
    • Server
    • Client

 

Server:

Import socket </P> <p> address = ('2017. 0.0.1 ', 31500) <br/> S = socket. socket (socket. af_inet, socket. sock_dgram) <br/> S. BIND (Address) </P> <p> while true: <br/> data, ADDR = S. recvfrom (2048) <br/> if not data: <br/> Print "client has exist" <br/> Break <br/> Print "Received:", data, "from", ADDR </P> <p> S. close () <br/>

Client:

Import socket </P> <p> address = ('2017. 0.0.1 ', 31500) <br/> S = socket. socket (socket. af_inet, socket. sock_dgram) </P> <p> while true: <br/> MSG = raw_input () <br/> if not MSG: <br/> Break <br/> S. sendto (MSG, address) </P> <p> S. close () <br/>

 

Running result:

 

Server

[Work@db-testing-com06-vm3.db01.baidu.com Python] $ Python udp_ss.py
Partitioned ed: aaaaaa from ('192. 0.0.1 ', 127)
Partitioned ed: 123456 from ('192. 0.0.1 ', 127)
Written ed: abcdef from ('192. 0.0.1 ', 127)

 

 

Client

[Work@db-testing-com06-vm3.db01.baidu.com Python] $ Python udp_cc.py
Aaaaaa
123456
Abcdef

[Python work@db-testing-com06-vm3.db01.baidu.com] $

 

========================================================== ========================================================

 

Reference: http://www.javaeye.com/topic/401391

Preface

Python is too convenient and easy to use. It supports a comprehensive third-party library with simple syntax. for developers, it is an essential tool for home travel and XXXX. I studied Python network support over the weekend and made a record for later reading.

 

Python supports BSD socket for network programming. Its API is similar to that in C. First, let's look at the TCP method. When it comes to network programming, it will certainly be designed for the server and client, respectively.

TCP Server

The general process of the server socket is as follows:

    1. Create a socket (you can select the socket type, such as Inet and UNIX, as well as the connection mode, TCP/UDP)
    2. Use bind to publish a port so that the client can easily connect
    3. Set the size of a listen queue
    4. Enter an infinite loop. In this infinite loop, use the accept function to wait for the client to connect. This function returns a new socket, corresponding to the client socket, and establishes a communication channel. Socket processing is generally placed in external independent functions (concurrency)
    5. Use send ()/Recv () to read and write the socket.

Let's take a look at the example below:

Python Code {
Function onclick ()
{
DP. Sh. toolbar. copytoclipboard (this); Return false;
}
} "Href =" http://www.javaeye.com/topic/401391 ">
  1. DefTcpserver ():
  2. Srvsock = socket. socket (socket. af_inet, socket. sock_stream)
  3. Srvsock. BIND (('',9527))
  4. Srvsock. Listen (5)
  5. While True:
  6. Clisock, (remotehost, remoteport) = srvsock. Accept ()
  7. Print "[% S: % s] connected"% (Remotehost, remoteport)
  8. # Do something on the clisock
  9. Clisock. Close ()
  10. If_ Name _ ="_ Main __":
  11. Tcpserver ()
Def tcpserver (): srvsock = socket. socket (socket. af_inet, socket. sock_stream) srvsock. BIND (', 9527) srvsock. listen (5) While true: clisock, (remotehost, remoteport) = srvsock. accept () print "[% s: % s] connected" % (remotehost, remoteport) # do something on the clisock. close () If _ name _ = "_ main _": tcpserver ()

 

Client
    1. Create a new socket
    2. Connect to the remote host using the connect function
    3. Perform I/O operations on this socket
Python code {
Function onclick ()
{
DP. Sh. toolbar. copytoclipboard (this); Return false;
}
} "Href =" http://www.javaeye.com/topic/401391 ">
  1. DefTcpclient ():
  2. Clisock = socket. socket (socket. af_inet, socket. sock_stream)
  3. Clisock. Connect (('Localhost',9527))
  4. # I/O on this clisock
  5. # Clisock. Send ("")
  6. # Dat = clisock. Recv (LEN)
  7. PrintDat
  8. If_ Name _ ="_ Main __":
  9. Tcpclient ()
Def tcpclient (): clisock = socket. socket (socket. af_inet, socket. sock_stream) clisock. connect ('localhost', 9527) # I/O on this clisock # clisock. send ("") # dat = clisock. recv (LEN) print dat if _ name _ = "_ main _": tcpclient ()

Python is simple to see from the amount of code. to convert this example into a file transmitter, you only need to add less than 20 lines of code.

UDP

UDP claims that there is no connection transmission, and it is not as complicated as TCP at all. There are no mechanisms such as three handshakes and error retransmission. Only sending, receiving, and receiving are allowed? I don't know. What should I do if the order is wrong? No matter! That's it, but the speed is much higher than TCP. Where data frames are not very demanding, this is indeed very useful, such as video transmission and audio transmission over the network.

Server
    1. Create a socket in the form of a Datagram
    2. Expose a port and connect to one client
    3. Start receiving data
Python code {
Function onclick ()
{
DP. Sh. toolbar. copytoclipboard (this); Return false;
}
} "Href =" http://www.javaeye.com/topic/401391 ">
  1. DefUdpserver ():
  2. Address = ('',9527)
  3. Srvsock = socket. socket (socket. af_inet, socket. sock_dgram)
  4. Srvsock. BIND (address)
  5. # Data, ADDR = srvsock. recvfrom (2048)
  6. If_ Name _ ="_ Main __":
  7. Udpserver ()
 
Def udpserver (): Address = (', 9527) srvsock = socket. socket (socket. af_inet, socket. sock_dgram) srvsock. BIND (Address) # data, ADDR = srvsock. recvfrom (2048) If _ name _ = "_ main _": udpserver ()

Note that the quotation marks in the address tuples in the server indicate that the datagram from any address can be accepted, and the TCP example indicates that the connection initiated by any address can be accepted.

Client
    1. Create a datagram socket
    2. Send and receive data
Python code {
Function onclick ()
{
DP. Sh. toolbar. copytoclipboard (this); Return false;
}
} "Href =" http://www.javaeye.com/topic/401391 ">
  1. DefUdpclient ():
  2. Address = ('Localhost',9527)
  3. Clisock = socket. socket (socket. af_inet, socket. sock_dgram)
  4. # Clisock. sendto (data, address)
  5. If_ Name _ ="_ Main __":
  6. Udpclient ()
 
Def udpclient (): Address = ('localhost', 9527) clisock = socket. socket (socket. af_inet, socket. sock_dgram) # clisock. sendto (data, address) If _ name _ = "_ main _": udpclient ()

The example given in this article already has a networkProgramIn practical applications, we should expand the socket processing. After all, socket is a concept with file handles, file descriptors, and pipeline descriptors, i/O processing can be performed on it. In fact, there is no difference in the form of socket operations and file handle operations in UNIX systems.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.