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 python3
2+ # -*- coding: utf-8 -*-
3+
4+ '用于练习网络编程TCP'
5+
6+ __author__ = 'sergiojune'
7+ import socket , threading , time
8+
9+ # 创建socket
10+ # s = socket.socket(socket.AF_INET , socket.SOCK_STREAM) # 第一个参数为指定ipv4模式, 第二个参数指定为tup模式的面向流
11+ # # 建立连接
12+ # s.connect(('www.sina.com.cn', 80))
13+ # # 发送请求
14+ # s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n') # 发送get请求,http协议
15+ # # 处理返回来的数据
16+ # buffer = []
17+ # while True:
18+ # # 指定最大接受1024个字节
19+ # d = s.recv(1024)
20+ # if d:
21+ # buffer.append(d)
22+ # else:
23+ # break
24+ # data = b''.join(buffer)
25+ # # 关闭连接
26+ # s.close()
27+ # 取出请求头和内容
28+ # header, body =data.split(b'\r\n')
29+ # print(header)
30+ # print(body)
31+
32+
33+ # 建立服务器端
34+ s = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
35+ # 绑定端口和地址,当有信息从这个端口发送过来时就捕捉
36+ s .bind (('127.0.0.1' , 9999 )) # 这个为本机ip,这个服务器只能接受本地的
37+ # 监听窗口
38+ s .listen (5 ) # 传入参数为最大的等待连接数
39+ print ('await for connect' )
40+ def tcplink (sock , add ):
41+ print ('here is a connector from %s:%s' % add )
42+ # 向客户端发送数据
43+ sock .send (b'Welcome' )
44+ # 处理客户端发送来的数据
45+ while True :
46+ d = sock .recv (1024 )
47+ time .sleep (1 )
48+ if not d or d == b'exit' :
49+ break
50+ sock .send (('hello %s !' % d .decode ('utf-8' )).encode ('utf-8' ))
51+ # 关闭连接
52+ sock .close ()
53+ print ('connect is closed' )
54+
55+ # 用永久循环来等待客户端连接
56+ while True :
57+ # 这个函数会返回一个客户端连接
58+ sock , add = s .accept ()
59+ # 创建线程来处理客户端的数据
60+ t = threading .Thread (target = tcplink , args = (sock , add ))
61+ # 开启线程
62+ t .start ()
You can’t perform that action at this time.
0 commit comments