zoukankan      html  css  js  c++  java
  • python tcp demo

    server

    # -*- coding: utf-8 -*-
    """
    Created on Mon Mar 28 22:28:29 2016
    @author: zhanghc
    """
    #引入模块
    import socket
    import threading
    import time
    
    def tcplink(sock,addr):
        print('Accept new connection from {0}:{0}...'.format(addr))
        sock.send('Welcome!')
        while True:
            data=sock.recv(1024)
            time.sleep(1)
            if data=='exit' or not data:
                break
            sock.send('Hello,%s!'%data)
        sock.close()
        print('Connection from {0}:{0} closed'.format(addr))
    
    #创建socket
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    
    #监听端口
    s.bind(('127.0.0.1',9999))
    s.listen(5)
    print('Waiting for connection...')
    
    while True:
        
        #接受一个新连接
        sock,addr=s.accept()
        
        #创建新线程来处理TCP连接
        t=threading.Thread(target=tcplink(sock,addr))

    输出:

    Waiting for connection...
    Accept new connection from ('127.0.0.1', 53535):('127.0.0.1', 53535)...
    Connection from ('127.0.0.1', 53535):('127.0.0.1', 53535) closed

    client

    # -*- coding: utf-8 -*-
    """
    Created on Mon Mar 28 22:40:41 2016
    
    @author: zhanghc
    """
    
    import socket
    
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    
    s.connect(('127.0.0.1',9999))
    
    print(s.recv(1024))
    
    for data in ['zhang','liu','wang']:
        s.send(data)
        print(s.recv(1024))
    
    s.send('exit')
    s.close()

    输出:

    Welcome!
    Hello,zhang!
    Hello,liu!
    Hello,wang!

  • 相关阅读:
    Task 5.1 电梯调度程序需求调研报告
    Task 4 求数组的连续子数组的最大和(团队合作)
    class 3 求数组中的最大值(单元测试)
    《你的灯亮着吗》读书笔记3
    优惠购书
    校友聊NABCD
    环状二维数组(改进版)
    环状二维数组
    环状一维数组
    二维数组最大值
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10315103.html
Copyright © 2011-2022 走看看