解析エンジニアの自動化 blog

コツコツと自動化した方法を残す blog

Python で通信プログラミング入門



こんにちは。
仕事の自動化にやりがいと達成感を感じるガッくんです。


この記事の目次



背景・目的


最近、簡単な通信プログラムの必要性を漠然と考えています。

スケジュールアプリなど色んなアプリに付いてたら良いなぁと思うので調べてみました。

調べていくとリンクのサイトが分かりやすくて、サイトの『(1)ソケットクライアントでHTTPリクエスト』をそのまま動かして理解してみることにしました。

Pythonでソケットを使った単一のソケットサーバー VS 複数のソケットクライアントの双方向チャット。 - Qiita



動作環境


Windows 10
・winpython 64bit 3.4.4



プログラム

ソースコード


###############################################################################
# HTTP リクエスト テストプログラム
###############################################################################
#==============================================================================
# ライブラリインポート
#==============================================================================
import socket
 
# ソケット作成 -------------------------------------------------------------------
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
# 接続先 -----------------------------------------------------------------------
host = "www.yahoo.co.jp"
port = 80
 
# 接続 -------------------------------------------------------------------------
sock.connect((host, port));
 
# リクエスト内容作成 --------------------------------------------------------------
req = "GET / HTTP/1.1" + "\r\n\r\n";
 
# リクエスト ----------------------------------------------------------------------
sock.send(req.encode("UTF-8"));
 
# リクエストのレスポンスを受信 --------------------------------------------------------
read_size = 128
res = "".encode("UTF-8")
while True:
    try:
        sock.settimeout(3)
        t = sock.recv(read_size);
        res += t
        if (len(t) == 0) :
            print(res.decode())
            print("====サーバーからの読み取り終了====")
            break;
    except Exception as e:
        print(e);



結果

コピペしただけのソースコードできちんと動作しているので、他のサンプルも難なく動いてくれそうな予感‼︎

ブラウザってすごいですね。


In [1]: runfile('C:/WinPython-64bit-3.4.4.6Qt5/settings/.spyder-py3/messenger000.py', wdir='C:/WinPython-64bit-3.4.4.6Qt5/settings/.spyder-py3')
timed out
timed out
timed out
HTTP/1.1 404 Not Found on Accelerator
Date: Tue, 04 Feb 2020 00:49:22 GMT
Connection: keep-alive
Via: http/1.1 edge1840.img.bbt.yahoo.co.jp (ApacheTrafficServer [c s f ])
Server: ATS
Cache-Control: no-store
Content-Type: text/html
Content-Language: en
X-Frame-Options: SAMEORIGIN
Content-Length: 6793
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<link rel="shortcut icon" href="https://s.yimg.jp/c/icon/s/bsc/2.0/favicon.ico" type="image/vnd.microsoft.icon" />
<link rel="icon" href="https://s.yimg.jp/c/icon/s/bsc/2.0/favicon.ico" type="image/vnd.microsoft.icon" />
<title>ページが表示できません - Yahoo! JAPAN</title>
<style type="text/css"><!--
/* yjTmplCommon */
body{margin:0;padding:0;text-align:center;font-family:"メイリオ", "ヒラギノ角ゴ", Helvetica, Arial, sans-serif;}dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,input,p,blockquote,fieldset,div{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}ul li, ol li{list-style:none;}table{margin:0;padding:0;border-collapse:collapse;border-spacing:0;font-size:100%;}caption{text-align:left;}table,pre,code,select,input,textarea,kbd,var,ins,del,samp{font-size:100%;}address,cite,dfn,em,strong,var,th,ins,del,samp{font-weight:normal;font-style:normal;}a img{border:0;}hr.yjSeparation{display:none;}fieldset{border:none;}#wrapper{text-align:left;font-size:medium;line-height:1.56;}#yjContentsBody{position:relative;}.yjGuid{display:block;height:0;overflow:hidden;font-size:0;line-height:0;text-indent:-9999px;}.yjSkip{display:block;height:0;overflow:hidden;font-size:0;line-height:0;text-indent:-9999px;}.yj950-1 #wrapper{ width:950px;margin:0 auto;padding:0 10px;}.yj950-1 #contents{text-align:left;}
 
/* fonts */
.s115{line-height:115%;}.s130{line-height:130%;}.s150{line-height:150%;}.yjXXL{font-size:x-large;voice-family:"\"}\"";voice-family:inherit;font-size:xx-large;font-size /**/:x-large;}html>body .yjXXL{font-size:180%;font-size/**/:xx-large;}.yjXL{font-size:large;voice-family:"\"}\"";voice-family:inherit;font-size:x-large;font-size /**/:large;}html>body .yjXL{font-size:150%;font-size/**/:x-large;}.yjL{font-size:medium;voice-family:"\"}\"";voice-family:inherit;font-size:large;font-size /**/:medium;}html>body .yjL{font-size:120%;font-size/**/:large;}.yjM{font-size:small;voice-family:"\"}\"";voice-family:inherit;font-size:medium;font-size /**/:small;}html>body .yjM{font-size:100%;font-size/**/:medium;}.yjMt{font-size:small;line-height:1.4em;voice-family:"\"}\"";voice-family:inherit;font-size:medium;font-size /**/:small;}html>body .yjMt{font-size:100%;font-size/**/:medium;}.yjS{font-size:x-small;voice-family:"\"}\"";voice-family:inherit;font-size:small;font-size /**/:x-small;}html>body .yjS{font-size:84%;font-size/**/:small;}.yjSt{font-size:x-small;line-height:1.3em;voice-family:"\"}\"";voice-family:inherit;font-size:small;font-size /**/:x-small;}html>body .yjSt{font-size:84%;font-size/**/:small;}.yjXS{font-size:xx-small;voice-family:"\"}\"";voice-family:inherit;font-size:x-small;font-size /**/:xx-small;}html>body .yjXS{font-size:70%;font-size/**/:x-small;}
 
/* masthead */
.yjmth{*height:1%;}.yjmth img{vertical-align:middle;border:0px;}.yjmth a{border:0px;}div.yjmthproplogoarea{float:left;}div.yjmthloginarea{float:left;margin:0px 0px 0px 3px;font-size:smaller;text-align:left;line-height:110%}div.yjmthcplogoarea{float:right;}div.yjmthcmnlnkarea{/*\*/float:right;/* */margin:10px 3px 0px 0px;font-size:smaller;text-align:right;line-height:110%;}br.yjmthclear{clear:both;}div.yjgrplink{text-align:right;font-size:smaller;line-height:115%;}div#music div.yjmthloginarea{margin-top:16px;margin-left:7px;}div#music div.yjmthcmnlnkarea{margin-top:26px;}div#music div.yjmthcplogoarea{margin-top:14px;}#masthead{width:100%;height:41px;margin:10px auto;text-align:left;}#masthead strong{font-weight:bold;}#masthead:after{content:"."; display:block; position:relative;height:0; clear:both; visibility:hidden;}/*\*/* html #masthead{height:1%;}* html #masthead .yjmth{margin:0;padding:0;}/**//* ie/mac \*//*/#masthead{display:inline-table;}/**/
@media print{div.yjmthloginarea{display:none;}}
 
/* footer */
#footer{text-align:center;}#footer address{padding:10px 0 20px;border-top:1px solid #ccc;font-size:small;line-height:1.4;}
 
/* contents */
.msg{margin:2.5em 0 4em;}.msg h1{font-size:130%;font-weight:bold;}.msg p{margin-top:2em;background-color:#fff;}.msg p.lnk{text-align:center;}
--></style>
</head>
<body class="yj950-1">
 
<div id="wrapper">
 
<div id="header">
<span class="yjGuid"><a name="yjPagetop" id="yjPagetop"></a><img src="https://s.yimg.jp/yui/jp/tmpl/1.1.0/audionav.gif" width="1" height="1" alt="このページの先頭です"></span>
<span class="yjSkip"><a href="#yjContentsStart"><img src="https://s.yimg.jp/yui/jp/tmpl/1.1.0/audionav.gif" alt="このページの本文へ" width="1" height="1" ></a></span>
<div id="masthead">
<div class="yjmth">
<div class="yjmthproplogoarea">
<a href="https://www.yahoo.co.jp/"><img src="https://s.yimg.jp/c/logo/f/2.0/yj_r_34.png" alt="Yahoo! JAPAN" width="136" height="34" border="0"></a></div>
<div class="yjmthcmnlnkarea">
<a href="https://www.yahoo.co.jp/">Yahoo! JAPAN</a>&nbsp;-&nbsp;<a href="https://www.yahoo-help.jp/">ヘルプ</a></div>
</div>
</div><!--/#masthead-->
 
</div><!--/#header-->
 
<hr class="yjSeparation">
 
<div id="contents">
 
<div id="yjContentsBody">
<span class="yjGuid"><a name="yjContentsStart" id="yjContentsStart"></a><img src="https://s.yimg.jp/yui/jp/tmpl/1.1.0/audionav.gif" alt="ここから本文です" width="1" height="1"></span>
 
<div id="yjMain">
<div class="yjMainGrid">
<div class="msg">
<h1>ページが表示できません</h1>
<p>障害が発生しているため、しばらくしてから、再度アクセスしてください。</p>
<p class="lnk"><a href="https://www.yahoo.co.jp/">Yahoo! JAPAN</a></p>
</div><!--/.msg-->
</div><!--/.yjMainGrid-->
</div><!--/#yjMain-->
 
</div><!--/#yjContentsBody-->
 
<div id="yjContentsFooter">
<span class="yjGuid"><img src="https://s.yimg.jp/yui/jp/tmpl/1.1.0/audionav.gif" width="1" height="1" alt="本文はここまでです"></span>
<span class="yjSkip">
<a href="#yjPagetop"><img src="https://s.yimg.jp/yui/jp/tmpl/1.1.0/audionav.gif" alt="このページの先頭へ" width="1" height="1"></a></span>
</div><!--/#yjContentsFooter-->
 
</div><!--/#contents-->
 
<hr class="yjSeparation">
 
<div id="footer">
<address><a href="https://privacy.yahoo.co.jp/">プライバシー</a> - <a href="https://about.yahoo.co.jp/docs/info/terms/">利用規約</a> - <a href="https://www.yahoo-help.jp/">ヘルプ・お問い合わせ</a><br>
Copyright (C) 2020 Yahoo Japan Corporation. All Rights Reserved.
</address>
</div><!--/#footer-->
 
</div><!--/#wrapper-->
 
</body>
</html>
 
====サーバーからの読み取り終了====
 
In [2]:



コメント

背景・目的に貼ったリンクを書いた方には本当に感謝致します。

通信系のプログラムは初めてだったのですが、非常にいい感触がつかめました。

誠にありがとうございます。



以上