SOCKET程式設計

20170405發表於2020-08-14

  加上迴圈的套接字通訊

  服務端應該滿足的特性:

  一直對外服務

  併發地提供服務

  import socket

  phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 在bind之前新增

  phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) # 重用ip和埠

  phone.bind('127.0.0.1', 8080)

  phone.listen(5)

  print(f'starting %s:%s'%('127.0.0.1', 8080))

  # 連結迴圈

  while True:

  conn, client_addr = phone.accept()

  print(client_addr)

  # 通訊迴圈

  while True:

  try:

  data = conn.recv(1024)

  # 針對linux系統

  if len(data) == 0:

  break

  print('收到客戶端資料:', data.decode('utd-8'))

  conn.send(data.upper())

  # 針對Windows系統

  except Exception:

  break

  conn.close()

  phone.close() # 關機

  客戶端:

  import socket

  phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  phone.connect(('127.0.0.1', 8080))

  while True:

  msg = input('>>>:').strip()

  phone.send(msg.encode('utd-8'))

  data = phone.recv(1024)

  print('服務端返回的資料:', data.decode('utd-8'))

  phone.close()

  5.3 遠端連線服務端並執行指令

  服務端:

  import socket

  import subprocess

  phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  phone.setsocketopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)

  phone.bind(('127.0.0.1', 8080))

  phone.listen(5)

  print('starting %s:%s'%('127.0.0.1', 8080))

  while True:

  conn, client_addr = phone.accept()

  print(client_addr)

  while True:

  try:

  cmd = coon.recv(1024)

  if len(cmd) == 0:

  break

  obj = subprocess.Popen(cmd.decode('utf-8'),

  shell = True,

  stdout = subprocess.PIPE,

  stderr = subprocess.PIPE)

  res1 = obj.stdout.read()

  res2 = obj.stderr.read()    

  conn.send(res1 if len(res2) == 0 else res2)

  except Exception:

  break

  conn.close()

  phone.close()

  客戶端:

  phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  phone.connect(('127.0.0.1', 8080))

  while True:

  cmd = input('[root@localhost]# ').strip()

  phone.send(cmd.encode('utf-8'))

  data = phone.recv(1024)

  print(data.decode('gbk))

  phone.close()


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69979119/viewspace-2711738/,如需轉載,請註明出處,否則將追究法律責任。

相關文章