socket是什么
Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求
想要深入了解的话,建议去看一下 TCP/IP协议详解第一卷,有了网络通信的基础更容易理解socket。
其实socket 可以这样理解,socket起源于unix/linux,而unix/linux的设计哲学 一部分就是 “一切皆文件”, 操作文件的时候都是
打开文件--》 操作文件 --》关闭文件
这样一个模式。socket就是该模式在网络通信上的一个具体实现。打一个比喻就是 两个人要打电话时用的电话。
python有两个基本的socket模块
socket #提供对网络通信的访问,该模块提供了一个底层的C API ,可以是用BSD套接字借口实现网络通信 SocketServer # 创建网络服务器,该模块是创建网络服务器的一个框架,
在《python标准库》 有详细的解释,(一本很使用的工具书,推荐大家看看)
一个简单的例子
socket_server.py
import socket obj = socket.socket() #创建套接字 obj.bind(("127.0.0.1",8342)) #绑定服务器地址信息 obj.listen() #开始监听 while True: conn,addr = obj.accept() # 等待一个链接过来 client_data = conn.recv() # 接收数据 client_data conn.send() # 发送数据 conn.close() # 关闭链接
socket_client.py import socket obj = socket.socket() # 创建套接字 obj.connect(("127.0.0.1",8342)) # 链接远程服务器 obj.send("im client") # 发送数据 ser_data = obj.recv(1024) # 接收服务器数据 print ser_data obj.close() #关闭套接字
实现过程:
服务端:
创建套接字,
将套接字绑定到服务器地址和端口上,这里是本地的ip和端口
监听链接信息
接收数据,处理数据,返回数据给客户端
关闭链接
客户端:
创建套接字
创建链接,链接到远程服务器
发送数据
接收数据,处理数据
关闭连接
关于socket模块涉及的方法(从help函数得来),不写写,似乎说不过去
|
| __init__(self, family=2, type=1, proto=0, _sock=None)
|
| accept(self)
| accept() -> (socket object, address info)
| 等待一个进入的链接,返回一个客户端的连接对象和地址
| Wait for an incoming connection. Return a new socket representing the
| connection, and the address of the client. For IP sockets, the address
| info is a pair (hostaddr, port).
|
| bind(...)
| bind(address)
| “”“ 将套接字绑定到ip和端口上”“”
| Bind the socket to a local address. For IP sockets, the address is a
| pair (host, port); the host must refer to the local host. For raw packet
| sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
|
| close(self, _closedsocket=<class ‘socket._closedsocket‘>, _delegate_methods=(‘recv‘, ‘recvfrom‘, ‘recv_into‘, ‘recvfrom_into‘, ‘send‘, ‘sendto‘), setattr=<built-in function setattr>)
| close()
| 关闭套接字
| Close the socket. It cannot be used after this call.
|
| connect(...)
| connect(address)
| 通过套接字链接到远程地址, 参数address的使用方式为(host, port)
| Connect the socket to a remote address. For IP sockets, the address
| is a pair (host, port).
|
| connect_ex(...)
| connect_ex(address) -> errno
|
| This is like connect(address), but returns an error code (the errno value)
| instead of raising an exception when an error occurs.
|
| dup(self)
| dup() -> socket object
|
| Return a new socket object connected to the same system resource.
|
| fileno(...)
| fileno() -> integer
|
| Return the integer file descriptor of the socket.
|
| getpeername(...)
| getpeername() -> address info
|
| Return the address of the remote endpoint. For IP sockets, the address
| info is a pair (hostaddr, port).
|
| getsockname(...)
| getsockname() -> address info
|
| Return the address of the local endpoint. For IP sockets, the address
| info is a pair (hostaddr, port).
|
| getsockopt(...)
| getsockopt(level, option[, buffersize]) -> value
|
| Get a socket option. See the Unix manual for level and option.
| If a nonzero buffersize argument is given, the return value is a
| string of that length; otherwise it is an integer.
|
| gettimeout(...)
| gettimeout() -> timeout
|
| Returns the timeout in seconds (float) associated with socket
| operations. A timeout of None indicates that timeouts on socket
| operations are disabled.
|
| listen(...)
| listen(backlog)
| 开始监听链接,
| Enable a server to accept connections. The backlog argument must be at
| least 0 (if it is lower, it is set to 0); it specifies the number of
| unaccepted connections that the system will allow before refusing new
| connections.
|
| makefile(self, mode=‘r‘, bufsize=-1)
| makefile([mode[, bufsize]]) -> file object
|
| Return a regular file object corresponding to the socket. The mode
| and bufsize arguments are as for the built-in open() function.
|
| sendall(...)
| sendall(data[, flags])
| 发送数据到套接字,调用的send() 函数来实现
| Send a data string to the socket. For the optional flags
| argument, see the Unix manual. This calls send() repeatedly
| until all data is sent. If an error occurs, it‘s impossible
| to tell how much data has been sent.
|
| setblocking(...)
| setblocking(flag)
|
| Set the socket to blocking (flag is true) or non-blocking (false).
| setblocking(True) is equivalent to settimeout(None);
| setblocking(False) is equivalent to settimeout(0.0).
|
| setsockopt(...)
| setsockopt(level, option, value)
|
| Set a socket option. See the Unix manual for level and option.
| The value argument can either be an integer or a string.
|
| settimeout(...)
| settimeout(timeout)
|
| Set a timeout on socket operations. ‘timeout‘ can be a float,
| giving in seconds, or None. Setting a timeout of None disables
| the timeout feature and is equivalent to setblocking(1).
| Setting a timeout of zero is the same as setblocking(0).
|
| shutdown(...)
| shutdown(flag)
|
| Shut down the reading side of the socket (flag == SHUT_RD), the writing side
| of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).
SocketServer 东西太多了 就不多说了 ,help一下自己看,你应该知道自学的重要性的。
大神博客地址
http://home.cnblogs.com/u/wupeiqi/
我的blog地址:
http://www.timesnotes.com/?p=143
本文出自 “Will的笔记” 博客,请务必保留此出处http://timesnotes.blog.51cto.com/1079212/1725424
python学习笔记-Day08--(socket和socketserver)
原文地址:http://timesnotes.blog.51cto.com/1079212/1725424