File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed
Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change 6060
6161### python_redis.py: Python操作Redis实现消息的发布与订阅
6262
63+ ### python_schedule.py: Python进行调度开发
64+
65+ ### python_socket.py: Python的socket开发实例
66+
6367### Plotly目录: 一些plotly画图的实例,使用jupyter notebook编写
68+
6469===================================================================================================
6570
6671### 您可以fork该项目, 并在修改后提交Pull request, 看到后会尽量进行代码合并
Original file line number Diff line number Diff line change 1+ # _*_ coding: utf-8 _*_
2+
3+ """
4+ Socket编程
5+ """
6+
7+ import sys
8+ import socket
9+
10+
11+ def server_func (port ):
12+ """
13+ 服务端
14+ """
15+ # 1. 创建socket对象
16+ server = socket .socket ()
17+
18+ # 2. 绑定ip和端口
19+ server .bind (("127.0.0.1" , port ))
20+
21+ # 3. 监听是否有客户端连接
22+ server .listen (10 )
23+ print ("服务端已经启动%s端口......" % port )
24+
25+ # 4. 接收客户端连接
26+ sock_obj , address = server .accept ()
27+ print ("客户端来自于:" , address )
28+
29+ while True :
30+ # 5. 接收客户端发送的消息
31+ recv_data = sock_obj .recv (1024 ).decode ("utf-8" )
32+ print ("客户端端(%s) -> 服务端: %s" % (address , recv_data ))
33+ if recv_data == "quit" :
34+ break
35+
36+ # 6. 给客户端回复消息
37+ send_data = "received[%s]" % recv_data
38+ sock_obj .send (send_data .encode ("utf-8" ))
39+ print ("服务端 -> 客户端(%s): %s" % (address , send_data ))
40+
41+ # 7. 关闭socket对象
42+ sock_obj .close ()
43+ server .close ()
44+
45+
46+ def client_func (port ):
47+ """
48+ 客户端
49+ """
50+ # 1. 创建客户端的socket对象
51+ client = socket .socket ()
52+
53+ # 2. 连接服务端, 需要指定端口和IP
54+ client .connect (("127.0.0.1" , port ))
55+
56+ while True :
57+ # 3. 给服务端发送数据
58+ send_data = input ("客户端>" ).strip ()
59+ client .send (send_data .encode ("utf-8" ))
60+ if send_data == "quit" :
61+ break
62+
63+ # 4. 获取服务端返回的消息
64+ recv_data = client .recv (1024 ).decode ("utf-8" )
65+ print ("服务端 -> 客户端: %s" % recv_data )
66+
67+ # 5. 关闭socket连接
68+ client .close ()
69+
70+
71+ if __name__ == '__main__' :
72+ flag = sys .argv [1 ]
73+ if flag == "server" :
74+ server_func (9901 )
75+ else :
76+ client_func (9901 )
You can’t perform that action at this time.
0 commit comments