zoukankan      html  css  js  c++  java
  • Python(九)之网络编程

    一般的网络通信:

    Python中利用socket模块实现网络主机间通讯:

    socket.socket(family,type)

    family:套接字类型

           AF_INET

           AF_UNIX

    type:

           STREAM:tcp 流式

           SOCK_DGRAM:udp 用户数据报

    基于TCP服务端编程:

    第一步:建立套接字对象:

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

    第二步:绑定地址

           使用套接字对象的bind方法绑定与某地址和端口

           tcpconn.bind((‘ip’,port))

           tcpconn.bind(('192.168.2.168',8089))

    第三步:使用listen方法进行监听

           tcpconn.listen(backlog)

           tcpconn.listen(100)

    第四步:循环监听状态

           使用套接字对象的accept方法接收用户请求

           ci,cp = tcpconn.accept()

           返回套接字对象和元组

    编写客户端程序:

    第一步,创建socket对象以连接服务器端

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

    第二步:

           clientsock.connect((‘server_ip’,port))

           clientsock.connect((‘192.168.2.168’,8089))

    第三步:发送请求

           clientsock.send()   

    一个简单的服务端和客户端编程的实现:

    服务端:mysocket.py

    #!/usr/local/bin/python
    import socket
    tcpconn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    server_addr = ('192.168.2.168',8089)
    tcpconn.bind(server_addr)
    tcpconn.listen(20)
    while True:
        cinfo,caddr = tcpconn.accept()
        print "Got a connect from %s" % caddr[0]
        data = cinfo.recv(1024)
        print "Receive data:%s" % data
        cinfo.send("My is server,your data is "+ data)
        cinfo.close()
    

     客户端:csocket.py

    #!/usr/local/bin/python
    import socket
    tcpconn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    server_addr = ('192.168.2.168',8089)
    tcpconn.bind(server_addr)
    tcpconn.listen(20)
    while True:
        cinfo,caddr = tcpconn.accept()
        print "Got a connect from %s" % caddr[0]
        data = cinfo.recv(1024)
        print "Receive data:%s" % data
        cinfo.send("My is server,your data is "+ data)
        cinfo.close()
    

     

  • 相关阅读:
    CF1324F Maximum White Subtree(树形dp)
    定时任务集群部署
    zookeeper服务的注册与发现
    多个定时任务服务注册到zookeeper临时顺序节点配置
    nginx反向代理
    nginx反向代理、负载均衡
    Eclipse快捷键
    下拉列表中复选框多选
    Zookeeper节点查看工具
    git打tag
  • 原文地址:https://www.cnblogs.com/jjzd/p/6936607.html
Copyright © 2011-2022 走看看