close

 

如何利用python 的Socket 來撰寫通程式

官方文件https://docs.python.org/2/howto/sockets.html
好站連接:(Server端)  http://www.binarytides.com/python-socket-programming-tutorial/


Server code

# -*- coding: big5 -*-

import socket                                       
from time import ctime

# create a socket object
serversocket = socket.socket(
         socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()                          

port = 9999                                          

# bind to the port
serversocket.bind((host, port))                                 

# queue up to 5 requests
serversocket.listen(5)  

while True:
  print 'waiting for connection...'
  tcpTimeClientSock, addr = serversocket.accept()
  print '...connected from:', addr

  while True:
    data = tcpTimeClientSock.recv(1024)
    if not data:  break
    print data
    reply = 'OK...' + data
    tcpTimeClientSock.send('[%s] %s' % (ctime(), reply))
   
   
  tcpTimeClientSock.close()
serversocket.close()

#----------------------

Client code

# -*- coding: big5 -*-

import socket
import sys

colors = ['red', 'green']

host = socket.gethostname()   
port = 9999                   # The same port as used by the server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))

while True:
  indata = raw_input('> ')
  if not indata:
      break
  sock.send(indata)
  data = sock.recv(1024)
  if not data:
      break
  print data
sock.close()

 

 

 

 

 

arrow
arrow
    文章標籤
    python socket
    全站熱搜

    stanley 發表在 痞客邦 留言(0) 人氣()