python Server programing

Python

Python3.xで作成のサーバー側プログラム

from __future__ import print_function
import socket
from contextlib import closing
import random


#温度
def get_temp():
    return random.randint(25, 70)


def main():
  host = '127.0.0.1'
  port = 4000
  backlog = 10
  bufsize = 4096
  print('Server Start')	
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  with closing(sock):
    sock.bind((host, port))
    sock.listen(backlog)
    while True:
      conn, address = sock.accept()
      with closing(conn):
        msg = conn.recv(bufsize)
        print(msg[0])
        if msg[0] == 97:# char is 'a'
            sys.exit(0)

        tmp = get_temp()
        stmp = str(tmp)
        moji = stmp.encode('utf-8')
        conn.send(moji)
        print( tmp )
  return

if __name__ == '__main__':
  main()
No tags for this post.
タイトルとURLをコピーしました