#!/usr/bin/env python
# -*- coding: sjis -*-
import os
import sys
import threading
from socket import socket, AF_INET, SOCK_STREAM
# AF_INET = Adress Family : Internet Sockets IPv4 を指す
# SOCK_STREAM = 通信プロトコル TCP を使用。 SOCK_DGRAM だと UDP
port = 50008
host = 'localhost'
stdoutmutex = threading.Lock()
def server():
sock = socket(AF_INET, SOCK_STREAM)
sock.bind(('', port)) # アドレスとポートを指定. '' は 'localhost' に置き換えても同じ模様
sock.listen(5) # 同時に接続できる個数
while True:
conn, addr = sock.accept()
data = conn.recv(1024) # bufsize
with stdoutmutex:
print data
reply = 'server got : [%s]\n' % data
conn.send(reply.encode())
def client(name):
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
sock.send(name.encode())
reply = sock.recv(1024)
sock.close()
with stdoutmutex:
print 'client got : [%s]' % reply
if __name__=='__main__':
argv = sys.argv
if len(argv) <= 1:
sys.exit(1)
elif argv[1] == '-s':
sthread = threading.Thread(target=server)
sthread.daemon = False
sthread.start()
elif argv[1] == '-c':
for i in range(5):
threading.Thread(target=client, args=('client % s' % i,)).start()
0 件のコメント:
コメントを投稿