Python core third edition of Network programming

Source: Internet
Author: User

To create a TCP server pseudo-code:

s = socket () #创建服务器套接字

S.bind () #套接字与地址绑定

S.listen () #监听连接

Inf_loop: #服务器无限循环

cs = s.accept () #接受客户端连接, if there is no connection, block

Comm_loop: #通信循环

CS.RECV ()/cs.send () #会话

Cs.close () #关闭客户端套接字

S.close () #关闭服务器套接字

Here's the code:

#!/usr/bin/env python3# encoding: utf-8from socket import *from time  import ctimehost =  ' port = 21567bufsize = 1024addr =  (HOST,  port) Tcpsersock= socket (af_inet, sock_stream) tcpsersock.bind (ADDR) Tcpsersock.listen (5) while  true:    print (' waiting for connection ... ')      Tcpclisock, addr = tcpsersock.accept ()     print (' ... connected from: ',  ADDR)     while true:        data =  TCPSERSOCK.RECV (BUFSIZE)         if not data:             break         tcpsersock.send (' [%s] %s '  %  (bytes (CTime (),  ' uft-8 '),  data)      tcpsersock.close () TcpseRsock.close () 

Create the TCP client pseudo-code accordingly:

CS = socket ()

Cs.connect ()

Comm_loop: #通信循环

CS.RECV ()/cs.send () #会话

Cs.close () #关闭客户端套接字

Here is the implementation code:

#!/usr/bin/env python

# Encoding:utf-8


From socket Import *


HOST = ' 192.168.184.130 '

PORT = 21567

BUFSIZE = 1024

ADDR = (HOST, PORT)


Tcpclisock = socket (af_inet, SOCK_STREAM)

Tcpclisock.connect (ADDR)

While True:

data = input (' > ')

If not data:

Break

Tcpclisock.send (data)

data = TCPCLISOCK.RECV (BUFSIZE)

If not data:

Break

Print (data)

Tcpclisock.close ()

On the basis of this simplest server socket program, it can be fully expanded.


Python core third edition of Network 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.