【小沐学python】开发环境(一) 【小沐学python】实现socket网络通信(二)
1、简介
Python 提供了两个级别访问的网络服务:
- 低级别的网络服务支持基本的 Socket,它提供了标准的 BSD Sockets API,可以访问底层操作系统 Socket 接口的全部方法。
- 高级别的网络服务模块 SocketServer, 它提供了服务器中心类,可以简化网络服务器的开发。
2、获取本机IP地址
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# filename:test_tcp_server.py
# creator: tomcat
# date: 2021-11-16
from socket import *
def get_host_ip():
s = 0
try:
s = socket(AF_INET, SOCK_DGRAM)
s.connect(('1.1.1.1', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
ip1 = get_host_ip()
print(ip1)
IP2 = gethostbyname(gethostname())
print(ip2)
3、TCP方式
3.1 服务端(只支持一个客户端访问)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# filename:test_tcp_server.py
# creator: tomcat
# date: 2021-11-16
from socket import *
from time import ctime
from datetime import datetime
HOST = ''
PORT = 27015
BUFSIZ = 1024
ADDR = (HOST, PORT)
s = socket(AF_INET, SOCK_STREAM)
s.bind(ADDR)
s.listen(5)
while True:
print('waiting for clients ...')
c, addr = s.accept()
t = datetime.now ().strftime ('%H:%M:%S')
print(' connnecting from: [', t, "]", addr)
while True:
data = c.recv(BUFSIZ)
if not data:
break
print("recv: ", data )
c.send(('[%s] %s' % (ctime(), "A message from python server.")).encode())
c.close()
s.close()
运行结果如下: 测试对应的客户端(C++),运行结果如下:
3.2 服务端(支持多个客户端并发访问,版本1)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# !/usr/bin/env python
# coding=utf-8
# filename:test_tcp_server.py
# creator: tomcat
# date: 2021-11-16
from socket import *
from time import ctime
from datetime import datetime
import threading
IP = gethostbyname(gethostname())
print("本机IP: ", IP)
ADDR = (IP, 12345)
BUFSIZ = 1024
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(ADDR)
s.listen(5)
socks = [] # 放每个客户端的socket
def handle():
while True:
for c in socks:
try:
data = c.recv(BUFSIZ)
except Exception as e:
continue
if not data:
socks.remove(c)
continue
st = datetime.now().strftime('%H:%M:%S')
print(" recv: %s, %s, %s" % (c.getpeername(), st, data))
c.send(('[%s],%s' % (ctime(), data)).encode())
t = threading.Thread(target=handle)
if __name__ == '__main__':
t.start()
print('waiting for connecting...')
while True:
clientSock, addr = s.accept()
print(' connected from:', addr)
clientSock.setblocking(False)
socks.append(clientSock)
s.close()
运行结果如下:
3.3 服务端(支持多个客户端并发访问,版本2)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# !/usr/bin/env python
# coding=utf-8
# filename:test_tcp_server.py
# creator: tomcat
# date: 2021-11-16
from socket import *
from time import ctime
from datetime import datetime
import threading
IP = gethostbyname(gethostname())
print("本机IP: ", IP)
ADDR = (IP, 12345)
BUFSIZ = 1024
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(ADDR)
s.listen(5) # 最大连接数
socks = [] # 放每个客户端的socket
def connect_handle(c, addr):
while True:
recvdata = c.recv(BUFSIZ)
if recvdata == 'exit' or not recvdata:
break
st = datetime.now().strftime('%H:%M:%S')
print(" recv: %s, %s, %s" % (c.getpeername(), st, recvdata))
msg = str(recvdata) + ' from python sever.'
c.send(msg.encode())
c.close()
while True:
c, c_addr = s.accept()
print(' connect from:', c_addr)
t = threading.Thread(target=connect_handle, args=(c, c_addr))
t.start()
s.close()
3.3 客户端
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# filename:test_tcp_client.py
# creator: tomcat
# date: 2021-11-16
from socket import *
from time import ctime
from datetime import datetime
BUFSIZ = 1024
ADDR = ('127.0.0.1', 27015) # or 'localhost'
c = socket(AF_INET, SOCK_STREAM)
c.connect(ADDR)
while True:
data = input('Input: ')
if not data:
break
c.send(data.encode())
data = c.recv(BUFSIZ)
if not data:
break
t = datetime.now().strftime('%H:%M:%S')
print("[", t,"]",data.decode('utf-8'))
c.close()
运行结果如下: 测试对应的服务端(C++),运行结果如下:
4、UDP方式
4.1 发送端
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# filename:test_udp_client.py
# creator: tomcat
# date: 2021-11-16
from socket import *
from datetime import *
BUFSIZ = 1024
ADDR = ('127.0.0.1', 27015) # or 'localhost'
c = socket(AF_INET, SOCK_DGRAM)
while True:
data = input('Input: ')
if not data:
break
c.sendto(data.encode(), ADDR)
data = c.recvfrom(BUFSIZ)
if not data:
break
t = datetime.now().strftime('%H:%M:%S')
print("[", t,"]", data)
c.close()
运行结果如下: 测试对应的接收端(C++),运行结果如下:
4.2 接收端
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# filename:test_udp_server.py
# creator: tomcat
# date: 2021-11-16
from socket import *
from time import ctime
from datetime import datetime
BUFSIZ = 1024
ADDR = ('127.0.0.1', 27015) # or 'localhost'
s = socket(AF_INET, SOCK_DGRAM)
s.bind(ADDR)
while True:
print('waiting for clients ...')
data, addr = s.recvfrom(1024)
t = datetime.now ().strftime ('%H:%M:%S')
print(' connnecting from: [', t, "]", addr)
data = data.decode()
if not data:
break
print('[Received]', data)
send = input('Input: ')
s.sendto(send.encode(), addr)
s.close()
运行结果如下: 测试对应的发送端(C++),运行结果如下:
5、HTTP方式
import requests
import base64
def acces_api_with_cookie(url_login,USERNAME,PASSWORD,url_access):
# Start a session so we can have persistant cookies
session = requests.session()
# This is the form data that the page sends when logging in
login_data = {
'username': USERNAME,
'password': PASSWORD,
'submit': 'login',
}
# Authenticate
r = session.post(url_login, data=login_data)
# Try accessing a page that requires you to be logged in
r = session.get(url_access)
#print r.content
#print r.text
print(r.status_code)
return r.content
#print r.content
id = 1
title = base64.b64encode("wuhan")
studytime = "a"
operat="b"
warning="c"
report="d"
table="portal_post"
url=base64.b64encode('{"action":"portal\/Article\/index","param":{"id":2}}')
url_full = "http://192.168.88.116/user/favorite/add?id="+str(id)\
+"&title="+title\
+"&studytime="+studytime\
+"&operat="+operat\
+"&warning="+warning\
+"&report="+report\
+"&table="+table\
+"&url="+url
print(url_full)
acces_api_with_cookie("http://192.168.88.116/user/login/dologin.html","admin","admin888", url_full)
6、WebSocket
The WebSocket Protocol enables two-way communication between a client running untrusted code in a controlled environment to a remote host that has opted-in to communications from that code. The security model used for this is the origin-based security model commonly used by web browsers. The protocol consists of an opening handshake followed by basic message framing, layered over TCP. The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (e.g., using XMLHttpRequest or s and long polling).
6.1 安装websockets库
$ pip install websockets
$ pip list
6.2 服务端
import asyncio
import websockets
async def main_loop(ws, path):
name = await ws.recv()
print(f"< {name}")
msg = f"Python server: {name}!"
print(f"> {msg}")
await ws.send(msg)
start_server = websockets.serve(main_loop, '127.0.0.1', 12345)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
运行结果如下: 测试对应的客户端(js)如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
<title></title>
<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script>
var ws;
$().ready(function () {
$('#conn').click(function () {
ws = new WebSocket($('#user').val());
$('#msg').append('<p>正在连接...</p>');
ws.onopen = function () {
$('#msg').append('<p>已经连接</p>');
}
ws.onmessage = function (evt) {
var myDate = new Date();
var mytime=myDate.toLocaleTimeString();
$('#msg').append('<p>' + mytime + ': ' + evt.data +'</p>');
}
ws.onerror = function (evt) {
$('#msg').append('<p>' + JSON.stringify(evt) + '</p>');
}
ws.onclose = function () {
$('#msg').append('<p>已经关闭</p>');
}
});
$('#close').click(function () {
ws.close();
});
$('#send').click(function () {
if (ws.readyState == WebSocket.OPEN) {
ws.send( $('#content').val() );
}
else {
$('#tips').text('连接已经关闭');
}
});
});
</script>
</head>
<body>
<div>
<input id="user" type="text" value='ws://127.0.0.1:12345' />
<input id="conn" type="button" value="连接" />
<input id="close" type="button" value="关闭"/><br />
<span id="tips"></span>
<input id="content" type="text" />
<input id="send" type="button" value="发送"/><br />
<div id="msg">
</div>
</div>
</body>
</html>
浏览器chrome的运行结果如下: Wireshark 抓取webscoket如下:
6.3 客户端
import asyncio
import websockets
async def main_loop():
async with websockets.connect('ws://localhost:12345') as ws:
name = input(">")
await ws.send(name)
print(f"> {name}")
msg = await ws.recv()
print(f"< {msg}")
asyncio.get_event_loop().run_until_complete(main_loop())
后记
如果你觉得该方法或代码有一点点用处,可以给作者点个赞;╮( ̄▽ ̄)╭ 如果你感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进。o_O??? 谢谢各位童鞋们啦( ′ ▽′ )ノ ( ′ ▽′)っ!!!
|