10.socket Programming Beginner

Source: Internet
Author: User

First, Socket introduction

The English literal of the socket is "hole" or "socket". As the BSD UNIX process communication mechanism, take the latter one meaning. Often also referred to as a "socket," which describes IP addresses and ports, is a handle to a communication chain that can be used to communicate between different virtual machines or different computers. Hosts on the internet typically run multiple service software, while providing several services. Each service opens a socket and binds to a port, and the different ports correspond to different services. The socket is like a porous socket, as its English intended. A host is like a room full of various sockets, each outlet has a number, some sockets provide 220 vac, some provide 110 volts AC, some provide cable TV programs. Customer software plug into different numbered sockets, you can get different services



Second, the principle of connection

depending on how the connection is started and the destination to which the local socket is connected, the connection between sockets can be divided into three steps: server Listening, client request, connection acknowledgement.

(1) Server monitoring: Is the server end socket does not locate the specific client socket, but in the status of waiting for the connection, real-time monitoring network status. (2) Client request: Refers to the client's socket to make a connection request, to connect to the target is the server-side socket. To do this, the client's socket must first describe the socket of the server it is connecting to, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket. (3) Connection confirmation: When the server-side socket is heard or received a client socket connection request, it responds to the client socket request, set up a new thread, the server-side socket description to the client, once the client confirms the description, the connection is established. While the server-side socket continues to be in the listening state, it continues to receive connection requests from other client sockets.
1. The simplest Web server
12345678910111213 #!/usr/bin/env python#coding:utf-8import socketip_port = (‘127.0.0.1‘,8080)web = socket.socket()web.bind(ip_port)web.listen(5)print (‘nginx waiting...‘)conn,addr = web.accept()while True:    data = conn.recv(1024)    conn.send(bytes(,‘utf8‘))    conn.close()

2. Simple Chat Tool

1) Service side

1234567891011121314151617181920212223242526 #!/usr/bin/env python#coding:utf-8import socket#开启ip和端口ip_port = (‘127.0.0.1‘,9999)#生成一个句柄sk = socket.socket()#绑定ip端口sk.bind(ip_port)#最多连接数sk.listen(5)#开启死循环while True:    print (‘server waiting...‘)    #等待链接,阻塞,直到渠道链接 conn打开一个新的对象 专门给当前链接的客户端 addr是ip地址    conn,addr = sk.accept()    #获取客户端请求数据    client_data = conn.recv(1024)    #打印对方的数据    print (str(client_data,‘utf8‘))    #向对方发送数据    conn.sendall(bytes(‘不要回答,不要回答,不要回答‘,‘utf8‘))    #关闭链接    conn.close()

2) Client Side

1234567891011121314151617 #!/usr/bin/env python#coding:utf-8import socket#链接服务端ip和端口ip_port = (‘127.0.0.1‘,9999)#生成一个句柄sk = socket.socket()#请求连接服务端sk.connect(ip_port)#发送数据sk.sendall(bytes(‘yaoyao‘,‘utf8‘))#接受数据server_reply = sk.recv(1024)#打印接受的数据print (str(server_reply,‘utf8‘))#关闭连接sk.close()
Third, more functions
123456789101112131415161718192021 更多功能sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)    参数一:地址簇       socket.AF_INET IPv4(默认)      socket.AF_INET6 IPv6      socket.AF_UNIX 只能够用于单一的Unix系统进程间通信    参数二:类型      socket.SOCK_STREAM  流式socket , for TCP (默认)      socket.SOCK_DGRAM   数据报式socket , for UDP      socket.SOCK_RAW 原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。      socket.SOCK_RDM 是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。      socket.SOCK_SEQPACKET 可靠的连续数据包服务    参数三:协议      0  (默认)与特定的地址家族相关的协议,如果是 0 ,则系统就会根据地址格式和套接类别,自动选择一个合适的协议
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 6667686970 sk.bind(address)  s.bind(address) 将套接字绑定到地址。address地址的格式取决于地址族。在AF_INET下,以元组(host,port)的形式表示地址。sk.listen(backlog)  开始监听传入连接。backlog指定在拒绝连接之前,可以挂起的最大连接数量。       backlog等于5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5      这个值不能无限大,因为要在内核中维护连接队列sk.setblocking(bool)  是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。 sk.accept()  接受连接并返回(conn,address),其中conn是新的套接字对象,可以用来接收和发送数据。address是连接客户端的地址。  接收TCP 客户的连接(阻塞式)等待连接的到来sk.connect(address)  连接到address处的套接字。一般,address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。sk.connect_ex(address)  同上,只不过会有返回值,连接成功时返回 0 ,连接失败时候返回编码,例如:10061sk.close()   关闭套接字sk.recv(bufsize[,flag])  接受套接字的数据。数据以字符串形式返回,bufsize指定最多可以接收的数量。flag提供有关消息的其他信息,通常可以忽略。sk.recvfrom(bufsize[.flag])  与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。sk.send(string[,flag])  将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。即:可能未将指定内容全部发送。sk.sendall(string[,flag])  将string中的数据发送到连接的套接字,但在返回之前会尝试发送所有数据。成功返回None,失败则抛出异常。      内部通过递归调用send,将所有内容发送出去。sk.sendto(string[,flag],address)  将数据发送到套接字,address是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。该函数主要用于UDP协议。sk.settimeout(timeout)  设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s sk.getpeername()   返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。sk.getsockname()  返回套接字自己的地址。通常是一个元组(ipaddr,port)sk.fileno()  套接字的文件描述符




















From for notes (Wiz)

10.socket Programming Beginner

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.