File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python
2+ # -*- coding: utf-8 -*-
3+
4+ 'a socket example which send echo message to server.'
5+
6+ import socket
7+
8+ s = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
9+ # 建立连接:
10+ s .connect (('127.0.0.1' , 9999 ))
11+ # 接收欢迎消息:
12+ print s .recv (1024 )
13+ for data in ['Michael' , 'Tracy' , 'Sarah' ]:
14+ # 发送数据:
15+ s .send (data )
16+ print s .recv (1024 )
17+ s .send ('exit' )
18+ s .close ()
Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python
2+ # -*- coding: utf-8 -*-
3+
4+ 'a server example which send hello to client.'
5+
6+ import time , socket , threading
7+
8+ def tcplink (sock , addr ):
9+ print 'Accept new connection from %s:%s...' % addr
10+ sock .send ('Welcome!' )
11+ while True :
12+ data = sock .recv (1024 )
13+ time .sleep (1 )
14+ if data == 'exit' or not data :
15+ break
16+ sock .send ('Hello, %s!' % data )
17+ sock .close ()
18+ print 'Connection from %s:%s closed.' % addr
19+
20+ s = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
21+ # 监听端口:
22+ s .bind (('127.0.0.1' , 9999 ))
23+ s .listen (5 )
24+ print 'Waiting for connection...'
25+ while True :
26+ # 接受一个新连接:
27+ sock , addr = s .accept ()
28+ # 创建新线程来处理TCP连接:
29+ t = threading .Thread (target = tcplink , args = (sock , addr ))
30+ t .start ()
Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python
2+ # -*- coding: utf-8 -*-
3+
4+ 'a socket example which get html data from www.sina.com.cn'
5+
6+ import socket
7+
8+ s = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
9+ # 建立连接:
10+ s .connect (('www.sina.com.cn' , 80 ))
11+ # 发送数据:
12+ s .send ('GET / HTTP/1.1\r \n Host: www.sina.com.cn\r \n Connection: close\r \n \r \n ' )
13+ # 接收数据:
14+ buffer = []
15+ while True :
16+ # 每次最多接收1k字节:
17+ d = s .recv (1024 )
18+ if d :
19+ buffer .append (d )
20+ else :
21+ break
22+ data = '' .join (buffer )
23+ # 关闭连接:
24+ s .close ()
25+
26+ header , html = data .split ('\r \n \r \n ' , 1 )
27+ print header
28+ # 把接收的数据写入文件:
29+ with open ('sina.html' , 'wb' ) as f :
30+ f .write (html )
You can’t perform that action at this time.
0 commit comments