1、Socket参数介绍

network socket is an endpoint of a connection across a computer network. Today, most communication between computers is based on the Internet Protocol; therefore most network sockets are Internet sockets. More precisely, a socket is a handle (abstract reference) that a local program can pass to the networking application programming interface (API) to use the connection, for example "send this data on this socket".

2、Socket参数介绍

socket.socket(family=AF_INETtype=SOCK_STREAMproto=0fileno=None)  必会

Create a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6AF_UNIXAF_CAN or AF_RDS. The socket type should beSOCK_STREAM (the default), SOCK_DGRAMSOCK_RAW or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted or in the case where the address family is AF_CAN the protocol should be one of CAN_RAW or CAN_BCM. If fileno is specified, the other arguments are ignored, causing the socket with the specified file descriptor to return. Unlike socket.fromfd()fileno will return the same socket and not a duplicate. This may help close a detached socket using socket.close().

socket.socketpair([family[, type[, proto]]])

Build a pair of connected socket objects using the given address family, socket type, and protocol number. Address family, socket type, and protocol number are as for the socket() function above. The default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET.

socket.create_connection(address[, timeout[, source_address]])

Connect to a TCP service listening on the Internet address (a 2-tuple (host, port)), and return the socket object. This is a higher-level function than socket.connect(): if host is a non-numeric hostname, it will try to resolve it for both AF_INET and AF_INET6, and then try to connect to all possible addresses in turn until a connection succeeds. This makes it easy to write clients that are compatible to both IPv4 and IPv6.

Passing the optional timeout parameter will set the timeout on the socket instance before attempting to connect. If no timeout is supplied, the global default timeout setting returned by getdefaulttimeout() is used.

If supplied, source_address must be a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If host or port are ‘’ or 0 respectively the OS default behavior will be used.

socket.getaddrinfo(hostportfamily=0type=0proto=0flags=0) #获取要连接的对端主机地址 必会

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 ,连接失败时候返回编码,例如:10061

sk.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() 

  套接字的文件描述符

socket.sendfile(fileoffset=0count=None)

     发送文件 ,但目前多数情况下并无什么卵用。

3. 基本Socket实例

server端(在linux上)

import socket,subprocess

server=socket.socket()
server.bind(('0.0.0.0',8000))
server.listen(5)
print("---waiting for client---")
while True:
conn,addr=server.accept() #conn就是客户端连过来而在服务端为其生成的一个连接实例
print(conn,addr)
while True:
try:
data=conn.recv(1024)
print("recv:",data.decode())
res_obj=subprocess.Popen(data,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
res=res_obj.stdout.read()
conn.send(str(len(res)).encode())
conn.send(res)
except Exception as e:
print(e)
break

client端

import socket
client = socket.socket()
client.connect(("localhost",8000))
while True:
msg=input(">>:").strip()
if len(msg)==0:continue
client.send(msg.encode())
data=client.recv(1024)
total_size=int(data.decode())
resive_size=0
res=b''
while resive_size<total_size:
d=client.recv(1024)
res+=d
resive_size+=len(d)
print(res.decode())

Socket网络编程一的更多相关文章

  1. Python学习笔记【第十三篇】:Python网络编程一Socket基础

    什么是⽹络 网络能把双方或多方连在一起的工具,即把数据从一方传递到另一方进行数据传递. 网络编程就是不同电脑上的软件能够进行数据传递.即进程间的通讯. 什么是TCP/IP协议 协议就是大家一起遵守的约 ...

  2. java网络编程基础——TCP网络编程一

    基于TCP协议的网络编程 TCP/IP协议是一种可靠的网络协议,它的通信的两端各自建立一个Socket,从而在通信的两端之间形成网络虚拟链路. Java使用Socket对象来代表两端的通信端口,并通过 ...

  3. QT 网络编程一

    QT如果要进行网络编程首先需要在.pro中添加如下代码:QT += network 在头文件中包含相关头文件 #include <QHostInfo> #include <QNetw ...

  4. vxworks下网络编程一:网络字节序问题

    inet_addr("192.168.1.1");//返回网络字节序整型ip地址inet_ntoa(saddr);//将包含网络字节序整型ip地址的in_addr对象转换成本地ch ...

  5. Linux 网络编程一(TCP/IP协议)

    以前我们讲过进程间通信,通过进程间通信可以实现同一台计算机上不同的进程之间通信. 通过网络编程可以实现在网络中的各个计算机之间的通信. 进程能够使用套接字实现和其他进程或者其他计算机通信. 同样的套接 ...

  6. Android初级教程理论知识(第八章网络编程一)

    网络图片查看器 确定图片的网址 发送http请求 URL url = new URL(address); //获取连接对象,并没有建立连接 HttpURLConnection conn = (Http ...

  7. Java网络编程一:基础知识详解

    网络基础知识 1.OSI分层模型和TCP/IP分层模型的对应关系 这里对于7层模型不展开来讲,只选择跟这次系列主题相关的知识点介绍. 2.七层模型与协议的对应关系 网络层   ------------ ...

  8. Java网络编程一

    1.InetAddress的应用 import java.util.List; import java.math.BigDecimal; import java.net.InetAddress; im ...

  9. Linux网络编程一、tcp三次握手,四次挥手

    一.TCP报文格式 (图片来源网络) SYN:请求建立连接标志位 ACK:应答标志位 FIN:断开连接标志位 二.三次握手,数据传输,四次挥手 (流程图,图片来源于网络) (tcp状态转换图,图片来源 ...

随机推荐

  1. PyVISA介绍

    针对测量仪器进行编程比较痛苦,存在各种各样的协议以及通过不同接口和总线(GPIB.USB.RS232).使用任何一种语言去编程,你必须找到支持仪器和对应总线的合适的库. 为了解决这种问题,VISA应运 ...

  2. C语言共用体、大小端、枚举

    1.共用体和结构体的相同和不同 (1)相同点就是操作语法几乎相同.(2)不同点是本质上的不同.struct是多个独立元素(内存空间)打包在一起:union是一个元素(内存空间)的多种不同解析方式. # ...

  3. iOS学习-UITextField设置placeholder的颜色

    UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(, , , )]; text.borderStyle = UITex ...

  4. 《UNIX环境高级编程》笔记——3.文件IO

    一.引言 说明几个I/O函数:open.read.write.lseek和close,这些函数都是不带缓冲(不带缓冲,只调用内核的一个系统调用),这些函数不输入ISO C,是POSIX的一部分: 多进 ...

  5. ajax两张传输数据方式

    encodeURI() 函数可把字符串作为 URI 进行编码. 语法 encodeURI(URIstring) 参数 描述 URIstring 必需.一个字符串,含有 URI 或其他要编码的文本. 返 ...

  6. ftp同步代码

    一个很naive的代码,用来做ftp的"主->从 下载,从->主 上传".ftp可不像mysql那样还有log可以用,所以完全naive的做法:连到ftp server ...

  7. Linux下常用压缩 解压命令和压缩比率对比

    常用的格式有:tar, tar.gz(tgz), tar.bz2, 不同方式,压缩和解压方式所耗CPU时间和压缩比率也差异也比较大. 1. tar只是打包动作,相当于归档处理,不做压缩:解压也一样,只 ...

  8. GStreamer 记录

    GStreamer 是一个新的多媒体框架,大大简化了多媒体工具的开发流程,比如,这里有一个 IBM 的文档,介绍了一个 MP3 播放器. http://www.ibm.com/developerwor ...

  9. java中获取路径的几种基本的方法

    package com.ygh.blog.realpath; import java.io.File; import java.io.IOException; import java.io.Input ...

  10. Rest webservice 和SOAP webservice

    SOAP: 简单对象访问协议(Simple Object Access Protocol,SOAP)是一种基于 XML 的协议,可以和现存的许多因特网协议和格式结合使用,包括超文本传输协议(HTTP) ...