Python Socket client and server Simple programming

Source: Internet
Author: User
Tags python script

This paper mainly introduces the simple implementation method of writing socket Server and Client using Python language.

1.PythonIntroduction to Socket Programming

Sockets are often also referred to as sockets, and applications usually make requests to the network through sockets or respond to network requests.

The three popular socket types are: Stream,datagram and raw. Stream and datagram sockets can interface directly with the TCP protocol, while the raw sockets interface to the IP protocol.

The Python socket module provides access to the low-level BSD socket style network, which is used to establish a simple server with TCP and streaming sockets.

2. Python SocketServer
#!/usr/bin/python# -*- coding: utf-8 -*-from socket import *def  Socketserver ():    try:        colon =  Serverurl.find (': ')         IP = ServerUrl[0:Colon]         port = int (serverurl[colon+1:])           #建立socket对象         print  ' server  start:%s '%serverurl        sockobj = socket (AF_INET,  SOCK_STREAM)         sockobj.setsockopt (SOL_SOCKET,SO_REUSEADDR, 1 )          #绑定IP端口号          Sockobj.bind ((ip, port))          #监听, 10 links allowed          sockobj.Listen (Ten)          #直到进程结束时才结束循环          while true:            # Wait for client link             connection, address  = sockobj.accept ( )              print  ' server connected by client: ', address             while True:                  #读取Client消息包内容                  DATA = CONNECTION.RECV (1024x768)                   #如果没有data, jumping out of the loop                  if not data: break                  #发送回复至Client                  res= ' 200 ok '                  connection.send (RES)                  print  ' receive msg:%s '%data.strip ()                 print  ' send res:%s\r\n '%res             #关闭Socket             connection.close ( )      except exception,ex:        print exserverurl  =  "202.96.100.113:9999 "Socketserver () 

Note : It is important to note that the socket object is created with Sockobj.setsockopt (SOL_SOCKET,SO_REUSEADDR, 1), or the Python script restarts after the socket ServerPortdoes not immediately close, appearsPortoccupyerror.

3. Python SocketClient

#!/usr/bin/python# -*- coding: utf-8 -*-from socket import *def  Socketclient ():    try:         #建立socket对象          s=socket (af_inet,sock_stream,0)          colon = serverurl.find (': ')         ip =  serverurl[0:colon]        port = serverurl[colon+1:]          #建立连接         s.connect ((Ip,int (Port)))         sdata= ' Get /test http/1.1\r\nhost:  %s\r\n\r\n '%serverurl        print  "Request:\r\n%s\r\n"% Sdata        s.send (sdata)          SRESULT=S.RECV (1024x768)         print  "response:\r\n%s\r\n"  %sresult          #关闭Socket         s.close ()      except exception,ex:        print exserverurl  =  "202.96.100.113:9999" socketclient ()


3. Running Results

The Socket server side runs as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/7B/06/wKiom1bFNM7ierznAAAlVS0OCwg271.png "title=" Qq20160218110436.png "alt=" Wkiom1bfnm7ierznaaalvs0ocwg271.png "/>


The Socket client side runs as follows:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7B/06/wKiom1bFNPWjSVP4AAAj4Vz7yvg012.png "title=" Qq20160218110526.png "alt=" Wkiom1bfnpwjsvp4aaaj4vz7yvg012.png "/>

This article is from the "Microsoft" blog, so be sure to keep this source http://1238306.blog.51cto.com/1228306/1742930

Python Socket client and server Simple programming

Related Article

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.