LoginSignup
48
53

More than 5 years have passed since last update.

PythonでSocket通信

Last updated at Posted at 2017-08-15

socket通信

1. socketを作る

  • IP: socket.AF_INET
  • TCP: socket.AF_INET, socket.SOCK_STREAM
  • UDP: socket.AF_INET, socket.SOCK_DGRAM

2. connectionを作る(TCPのみ)

  • TCP server: bind, listen, accept
  • TCP client: connect

3. 送受信する

  • TCP: send, recv
  • UDP: sendto, recvfrom

例:TCP通信

googleのページをhttp getで取得

tcp.py
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("www.google.co.jp",80))
client.send(b"GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
response = client.recv(4096)
print(response)

例:UDP通信

localserverに"12345"を送信。

udp-client.py
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"12345",("127.0.0.1",80))

data, addr = client.recvfrom(4096)
print(data)

例:TCPサーバー

ポート5000で待ち受けて、現在時刻を返す

tcp-server.py
import socket
from datetime import datetime
from time import sleep

s = socket.socket()

port = 5000
s.bind(('', port))

while True:
    print('listening')
    s.listen(5)
    c, addr = s.accept()
    print('receiving')
    print(c.recv(4096))
    while True:
        print('sending')
        now = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
        try:
            c.send(now)
        except:
            break
        sleep(1)
    c.close()
s.close()
tcp-client.py
import socket
from contextlib import closing
import sys

s = socket.socket()

host = sys.argv[1]
port = 5000

#with closing(s):
s.connect((host, port))
s.send("hi")
while True:
    print host, s.recv(4096)
48
53
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
48
53