Python writes socket server and client

Source: Internet
Author: User

The main module used this time is the socket module, where you can find the socket () function, which is used to create a socket object. Sockets also have their own set of methods that can implement socket-based network communication.


Socket () module function

To create a socket, you must use the Socket.socket () function with the following syntax:

socket (socket_family,socket_type,protocol=0)

Where socket_family is Af_unix (file-based) or af_inet (network-oriented), Socket_type is Sock_stream (TCP) or Sock_dgram (UDP), protocol is usually omitted, default is 0


Example: Create a TCP/IP socket:

Tcpsock = Socket.socket (socket.af_inet,socket. SOCK_STREAM)

To create a UDP/IP socket:

Udpsock = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)


Create a TCP timestamp server and client

#  Server from socket import * from time import ctimehost =  "                                            #  NULL indicates that any available address can be used port = 21567                                        #  Listening Port bufsiz =  1024                                       #  buffer size addr =  (host,port) tcpsersock = socket (Af_inet,sock_stream)           #  assigning TCP server sockets Tcpsersock.bind (addr)                                #  Bind server address Tcpsersock.listen (5)                                 #  Turn on TCP listener call try:    while true:                                     #  into the loop, waiting for the client to connect          print  ' Waiting for connection '          tcpclisock,addr = tcpsersock.accept ()      #   Connection Request         print  ' ... connection from: ',addr         while True:            data  = TCPCLISOCK.RECV (bufsiz)         #  get Messages      if not data:                           #  message is empty, exit          break    tcpclisock.send (' [%s] %s '% (CTime (), data) )  #  message exists, then add time stamp and return Data         tcpclisock.close ()      except KeyboardInterrupt:                          # ctrl+c exit      print  ' you&Nbsp;have ctrl+c,quit now '     tcpsersock.close () 
#  client from socket import *host =  ' localhost '                                   # host,port is the server hostname and port port = 21567bufsiz =  1024addr =  (Host,port) tcpclisock = socket (af_inet,sock_stream)            #  assigning TCP client sockets Tcpclisock.connect (addr)                             #  actively call and connect to the server try:    while true:         data = raw_input (' >  ')                      #  Input String          if not data:    break         Tcpclisock.send (data)                       #  Send to Server         data  = TCPCLISOCK.RECV (Bufsiz)             #   Get Server Data         if not data:     break        print dataexcept keyboardinterrupt:     print  ' You have ctrl+c,quit now '     tcpclisock.close ()


Executing the TCP server and client

# client [[email protected] python]# python tcp_client.py > Hi[thu 11:11:04] hi> welcome! [Thu 11:11:10] Welcome!>

# server-side [[email protected] python]# python tcp_server.py waiting for connection......connection from: (' 127.0.0.1 ', 52900) W Aiting for connection ...


Create a UDP timestamp server and client

#  Server from socket import * from time import ctimehost =  " port = 21567bufsiz = 1024addr =  (Host,port) udpsersock = socket (AF_INET , Sock_dgram)             #  Assigning UDP server sockets Udpsersock.bind (addr)                                #  UDP is not connected, so there is no need to listen try:    while true:         print  ' Waiting for message ... '         data,addr =  udpsersock.recvfrom (bufsiz)     #  get messages, process and return clients          udpsersock.sendto (' [%s] %s '% (CTime (), data), addr)          print  ' ... received fRom and return to: ',addrexcept keyboardinterrupt:    print  ' you  have ctrl+c,quit now '     udpsersock.close ()
#  client from socket import * host =  ' localhost ' port = 21567bufsiz  = 1024addr =  (Host,port) udpclisock = socket (Af_inet,sock_dgram)             #  assigning UDP sockets try:                             while True:                                     #  works almost like a TCP client         data  = raw_input (' >  ')          if not data:     break        udpclisock.sendto (DATA,ADDR)          data,addr = udpclisock.recvfrom (Bufsiz)          if not data:            break         print dataexcept KeyboardInterrupt:     print  ' You have ctrl+c,quit now '     udpclisock.close ()


Execution results

# client [[email protected] python]# python udp_client.py > 123[thu 11:23:01] 123> hello[thu 11 11:23:04 ] Hello>
# server-side [[email protected] python]# python udp_server.py waiting for message......received from and return to: (' 127.0.0.1 ', 55532) waiting for message......received by and return to: (' 127.0.0.1 ', 55532) waiting for message ...


Python writes socket server and client

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.