Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SystemsAndroidRobotics/a24cb3b3dffe5092e61bae72d713afbc to your computer and use it in GitHub Desktop.
Save SystemsAndroidRobotics/a24cb3b3dffe5092e61bae72d713afbc to your computer and use it in GitHub Desktop.
非常に単純なUDP受信コード
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"UDP通信でデータを受信する最も単純なコード Hisashi Ishihara 2018-04-24"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import socket #通信用\n",
"\n",
"address = ('127.0.0.1', 1308) #通信を受け付けるIPアドレスと受信に使うポート番号の設定.127.0.0.1とするとPC内通信.\n",
"\n",
"udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #udpという名前のUDPソケット生成\n",
"udp.bind(address) #udpというソケットにaddressを紐づける\n",
"\n",
"while True: #受信ループ\n",
" try:\n",
" rcv_byte = bytes() #バイトデータ受信用変数\n",
" rcv_byte, addr = udp.recvfrom(1024) #括弧内は最大バイト数設定\n",
" msg = rcv_byte.decode() #バイトデータを文字列に変換\n",
" print(msg) #文字列表示\n",
" if msg == 'close': #受信した文字列がcloseならUDPソケットを閉じて終了\n",
" udp.close()\n",
" break\n",
" except KeyboardInterrupt:#強制終了を検知したらUDPソケットを閉じて終了\n",
" udp.close()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment