TCP Programming Learning in Python

Source: Internet
Author: User

Today we have a look at TCP programming for Python. The idea of finding ideas is almost the same as other languages (like Java).

Look at the client first. The basic steps are as follows:

  • First step: Create a socket
  • Step two: Establish a connection
  • Step three: Send data
  • Fourth step: Read the data sent from the server
  • Fifth step: Close the connection
  • Sixth step: processing the Received data

Below is a small example of a Python-programmed client program for TCP. See here for a blog post on network programming in Java

#coding: Utf-8#TCP编程的客户端程序#编写客户端程序与其它语言 (for example, Java) have similar ideas. as follows#第一步: Create a socketImportSockets=Socket.Socket(Socket. Af_inet,Socket. SOCK_STREAM)#第二步: To establish a connection, the parameter is a tuple to access Sina for examples.Connect((' www.sina.com.cn ', the))#80端口是Web服务的标准端口#第三步: Send datas.Send(b' get/http/1.1\r\n host:www.sina.com.cn\r\nconnection:close\n\r\n ')#第四步: Receiving dataBuffer=[] whileTrue:d=s.recv(1024x768)#recv (max) method, which means that only max bytes can be read at a time    ifD:buffer.append (d)Else: BreakDate=b"'.Join(buffer)#第五步: Close the connections.Close()#第六步: Processing the data received by the docking#由于接收到的数据包括http头和网页本身, so separate itHeader,html=date.Split(b' \r\n\r\n ',1)Print(Header.decode (' Utf-8 ')) withOpen(' sina.html ',' WB ') as F:f.Write(HTML)

The following view of the server-side program, the idea is as follows

  • First step: Create a socket
  • Step two: Bind the listening address and port, method bind () only receives one tuple
  • Step three: Call the Listen () method to start listening on the port, the incoming parameter specifies the maximum number of waiting connections
  • Fourth step: The server program receives from the client through a permanent loop, and the Accept () waits for and returns a client connection
#python中的服务器端的程序, the client program used for testing is: tcpclient1.py#coding: Utf-8ImportSocketImportThreading def tcplink(sock,addr):Print' Accept new connection from%s:%s ... '%ADDR) Sock.send (B ' Welcome ') while True: Date=sock.recv (1024x768)if  notDateorDate.decode (' Utf-8 ')==' exit ': BreakPrint (Date.decode (' Utf-8 ')) Sock.close () print (' Connection from%s:%s '%ADDR)#第一步: Create a socketS=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#第二步: Bind the listening address and port, method bind () only receives one tupleS.bind ((' 127.0.0.1 ',9999))#第三步: Call the Listen () method to start listening on the port, the incoming parameter specifies the maximum number of waiting connectionsS.listen (Ten)#第四步: The server program receives a permanent loop to receive from the client, and accept () waits for and returns a client connection while True: Sock,addr=s.accept ()#创建一个新线程来处理TCP链接Threading. Thread (target=tcplink,args= (SOCK,ADDR)). Start ()

Test the above server-side program, we use a simple client program to test, as follows

#为tcpServer服务器端写一个测试的客户端程序#coding: Utf-8ImportSocket#第一步: Create a sockets=Socket.Socket(Socket. Af_inet,Socket. SOCK_STREAM)#第二步: Establishing a connections.Connect((' 127.0.0.1 ',9999))#第三步: Send datas.Send(b' Hello world! ')#第三步: Receiving dataDate=s.recv(1024x768)Print(Date.decode (' Utf-8 '))

Just a few days ago the system to learn a Git version control this tool, so, began to run my github, the above code can be downloaded in my GitHub, click here to

The reference address is as follows: A detailed introduction to TCP programming Http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 001432004374523e495f640612f4b08975398796939ec3c000

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

TCP Programming Learning in Python

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.