Python socket编程之一:

  • soket 编程步骤
# -*- coding: utf-8 -*-
########################################################################
class sckt:
    """去元音缩写变量名 sckt 指代 socket """
    #----------------------------------------------------------------------
    def __init__(self, host = '192.168.1.3', port = 12345):
        print("""地址初始化...""")
        self.host = host
        self.port = port
    #----------------------------------------------------------------------
    def run_server(self):
        print("""运行服务器...""")
        import socket
        print("""第一步:创建 socket 对象""")
        sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print("""第二步:将 socket 绑定到指定地址""", self.host, self.port)
        sckt.bind((self.host, self.port))
        print("""第三步:使用 socket 套接字的 listen 方法接收连接请求""")
        sckt.listen(5)
        while True:
            print("""第四步:通过 socket 的 accept 方法等待客户请求一个连接""")
            connection, address = sckt.accept()
            try:
                print("""第五步:处理阶段,服务器和客户端通过 send 和 recv 方法通信""")
                connection.settimeout(5)
                buffer = connection.recv(1024)
                print(buffer)
                if buffer == b'Link':
                    connection.send(b'Welcome to server!')
                else:
                    connection.send(b'Message form client: ' + buffer)
            except socket.timeout:
                print(b'Time out!')
            print("""最后是:传输结束,服务器调用 socket 的 close 方法关闭连接...""")
            connection.close()
    #----------------------------------------------------------------------
    def run_client(self, message = b'Link'):
        print("""运行客户端...""")
        import socket
        print("""第一步:创建 socket 对象""")
        sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print("""第二步:连接服务器""", self.host, self.port)
        sckt.connect((self.host, self.port))
        import time
        time.sleep(2)
        print("""第三步:通信""")
        sckt.send(message)
        print(sckt.recv(1024))
        print("""最后是:关闭连接...""")
        sckt.close()
  • 通过 cmd 查询地址、端口状态

360截图20160528162457656

  • 运行效果
# -*- coding: utf-8 -*-
"""加载路径"""
import sys
sys.path.append('D:\360data\重要数据\桌面')
"""加载模块"""
import sckt
"""实例化"""
SCKT = sckt.sckt()
"""运行服务器"""
SCKT.run_server()
"""运行客户端"""
SCKT.run_client()

1

2

附流程图:

48

posted @ 2016-05-28 14:40  佩雷尔曼的信徒  阅读(209)  评论(0编辑  收藏  举报