socket通常也称作套接字,用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过“套接字”向网络发出请求或者应答网络请求
socket既是一种特殊文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)
socket和file的区别
file模块是针对某个指定文件进行【打开】【读写】【关闭】
socket模块是针对服务器端和客户端socket进行【打开】【读写】【关闭】
实例:
在wen页面中访问
返回http 1.1 200 OK和HelloWorld
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#!/usr/bin/env python #coding:utf-8 import socket
def handle_request(client):
client.send( "HTTP/1.1 200 OK\r\n\r\n" )
client.send( "Hello, World" )
def main():
# 创建sock对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 监听端口
sock.bind(( 'localhost' , 8080 ))
# 开始监听
sock.listen( 5 )
while True :
# 阻塞,等连接的请求,直到有请求来连接
# connection:代表客户端sock的对象
# address:客户端IP地址
connection, address = sock.accept()
buf = connection.recv( 1024 )
print buf
connection.send( 'http1.1 200 OK\r\n\r\n' )
connection.send( "Hello World" )
connection.close()
if __name__ = = '__main__' :
main()
|
实例:10086服务
服务端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import socket
ip_port = ( '127.0.0.1' , 8888 )
sk = socket.socket()
sk.bind(ip_port) sk.listen( 5 )
while True :
conn,address = sk.accept()
conn.sendall( '欢迎致电 10086,请输入1xxx,0转人工服务.' )
Flag = True
while Flag:
data = conn.recv( 1024 )
if data = = 'exit' :
Flag = False
elif data = = '0' :
conn.sendall( '通过可能会被录音.........一大推' )
else :
conn.sendall( '请重新输入.' )
conn.close()
|
客户端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import socket
ip_port = ( '127.0.0.1' , 8888 )
sk = socket.socket()
sk.connect(ip_port) sk.settimeout( 5 )
while True :
data = sk.recv( 1024 )
print 'receive:' ,data
inp = raw_input ( 'please input:' )
sk.sendall(inp)
if inp = = 'exit' :
break
sk.close() |