Get google page with 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)
Send "12345" to localserver.
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)
Listen on port 5000 and return the current time
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)
Recommended Posts