码迷,mamicode.com
首页 > 编程语言 > 详细

python socket编程tcp/udp俩连接

时间:2018-05-24 15:07:15      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:end   close   recv   发送数据   accept   __name__   import   tin   bsp   

#服务端代码

 

import socket, threading
import time

‘‘‘
#服务端 TCP连接

def tcplink(sock, addr):
    print(‘Accept new connection from %s:%s...‘ % addr)
    sock.send(b‘Welcome!‘)
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if not data or data.decode(‘utf-8‘) == ‘exit‘:
            break
        sock.send((‘Hello, %s!‘ % data.decode(‘utf-8‘)).encode(‘utf-8‘))
    sock.close()
    print(‘Connection from %s:%s closed.‘ % addr)


if __name__ == ‘__main__‘:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((‘localhost‘, 9999))
    s.listen(5)
    print(‘Waiting for connecting ...‘)
# while True:
    sock, addr = s.accept()
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()
‘‘‘


# 服务端UDP
if __name__ == __main__:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 绑定端口:
    s.bind((127.0.0.1, 9999))
    print(Bind UDP on 9999...)
    while True:
        # 接收数据:
        data, addr = s.recvfrom(1024)
        print(Received from %s:%s. % addr)
        s.sendto(bHello, %s! % data, addr)

 

 

 

 

 

# 客户端代码

import socket

# tcp连接
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((‘127.0.0.1‘, 9999))
# print(s.recv(1024).decode(‘utf-8‘))
# for data in [b‘Micheal‘, b‘Tracy‘, b‘Sarah‘]:
#     s.send(data)
#     print(s.recv(1024).decode(‘utf-8‘))
# s.send(b‘exit‘)
# s.close()
#


# udp连接
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for data in [bMichael, bTracy, bSarah]:
    # 发送数据:
    s.sendto(data, (127.0.0.1, 9999))
    # 接收数据:
    print(s.recv(1024).decode(utf-8))
s.close()

 

 

 

 

  

 

  

 

python socket编程tcp/udp俩连接

标签:end   close   recv   发送数据   accept   __name__   import   tin   bsp   

原文地址:https://www.cnblogs.com/ceshixuexi/p/9082526.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!