Python Socket Network Programming TCP/IP server communicates with client

Source: Internet
Author: User
Python Socket Network Programming

Beginner python, a time ago bought two books, "Python programming from the beginning to practice," "The third version of Python core programming," the first book is mainly about some basic grammar and some basic use, and the second one is much deeper, it seems to be smattering, just see this part of the network programming, There are still a lot of not understand the place, but want to through their own constant groping, constantly searching for information learning, sooner or later should become transparent bar ....

This part of the main module is the socket module, in this module can find the socket () function, which is used to create socket objects, sockets also have their own set of methods, these methods can be implemented based on the network communication socket.

Socket () module function

To create a socket, you must use the Socket.socket () function, and his general syntax is as follows

Sockets (Socket_family, Socket_type, protocol=0)

Where socket_family is Af_unix or Af_inet,socket_type is Sock_stream or sock_dgram,protocol is usually omitted, the default =0.

Therefore, to create a TCP/IP socket, you can call Socket.socket () using the following method.

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

Similarly, create a UDP/IP socket, using the following method to invoke the

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

Create a TCP server

The process of creating a TCP server is basically the following, not just real code

SS = socket ()          #创建服务器套接字    ss.bind ()              #套接字与地址绑定    ss.listen ()             #监听连接    inf_loop:             #服务器无限循环        cs = Ss.accepr ()   #接受客户端连接        comm_loop:      #通信循环            cs.recv ()/cs.send ()   #对话 (Receive/Send)        Cs.close ()        #关闭客户端套接字    ss.close ()            #关闭服务器套接字 (optional)

In practice, the basic process of creating a TCP server is as above, it may be slightly different, but the basic idea should be the same, the following is the real code of the server:

#!/usr/bin/env python#-*-coding:utf-8-*-from Socket import *      #将 socket attribute introduced into namespace host = '          #这是对 the identity representation of the bind () method can be Use any available address PORT = 21571      #端口号BUFSIZ = 1024x768     #缓冲区大小, 1kbADDR = (host,port)   #地址???? Tcpsersocket = socket (af_inet,sock_stream)    #创建 TCP socket Tcpsersocket.bind (ADDR)           # Bind address to socket on Tcpsersocket.listen (5)            #设置并启动套接字监听while True:        #无限循环, waiting for client to connect  print (' Waiting for connection ... ')     tcpclisocket,addr = tcpsersocket.accept ()    #被动接受客户端连接       print (' ... connected from: ', addr)  While True:      #对话循环, waits for the client to send the message    data = TCPCLISOCKET.RECV (bufsiz)   #接收客户端消息    if not data:     # If the message is blank, jump out of the conversation loop, close the current connection, break    tcpclisocket.send (data)   #如果收到消息, and return the message intact to the client  Tcpclisocket.close () Tcpsersocket.close ()

Create a TCP client

As with the top, a simple non-code process

CS = socket ()    #创建客户端套接字    cs.connect ()     #尝试连接服务器    comm_loop:     #通信循环        cs.send ()/cs.recv ()  # Dialog (send/Receive)    Cs.close ()       #关闭客户端套接字

Creating a client in practice is also a translation of the top steps

#!/usr/bin/env python#-*-coding:utf-8-*-from socket import *host = ' localhost '    #服务器的主机名PORT = 21571     #端口号BUFSI Z = 1024x768     #缓冲区ADDR = (host,port)   #地址tcpCliSocket = socket (af_inet,sock_stream)  # Create client Socket Tcpclisocket.connect (ADDR)     #连接服务器while True:        #通信循环  data = input (' > ')    #客户端输入信息  if not data:   #如果输入信息为空, jump out of the loop, turn off communication break  data = str.encode (data)        tcpclisocket.send (data)   #发送客户端信息  data = TCPCLISOCKET.RECV (bufsiz)   #接受服务器返回信息  if not data:    #如果服务器未返回信息, turn off the communication loop    Break  print (' Get: ', Data.decode (' Utf-8 ')) Tcpclisocket.close ()

Of course, this is only the most basic communication, and about the host name, port number and other things are not very understanding, the current do is only in the same computer communication, the port number needs to be consistent, if different computers to communicate how to do? I'm just a little white ...

Thank you for reading, hope to help everyone, thank you for the support of this site!

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.