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

python 学习5 网络编程-TCP/UDP

时间:2015-01-20 17:33:36      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

摘抄自:廖雪峰的官方网站:http://www.liaoxuefeng.com/

TCP客户端和服务器端代码:


 

#coding=utf-8
#客户端程序TCP 连接

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 [Michael,Tracy,Sarah]:
    s.send(data.encode())
    print(s.recv(1024))

s.send(bexit)
#coding=utf-8
#TCP服务器端程序
import socket
import time
import threading



def tcplink(sock,addr):
    print("accept new connection from %s:%s..." % addr)
    sock.send("Welcom!".encode())
    while True:
        data=sock.recv(1024)
        time.sleep(1)
        if data==exit or not data:
            break
        sock.send("hello: ".encode()+data)
    sock.close()
    print("Connection from %s:%s closed." % addr)
    
    
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)  # 创建一个基于ipv4 的TCP协议的socket

s.bind((127.0.0.1,9999))  #监听端口

s.listen(5)
print("Waiting for connection......")

while True:
    sock,addr=s.accept()
    t=threading.Thread(target=tcplink,args=(sock, addr))
    t.start()
    

运行结果:

Waiting for connection......
accept new connection from 127.0.0.1:60218...
Connection from 127.0.0.1:60218 closed.
bWelcom!
bhello: Michael
bhello: Tracy
bhello: Sarah

 

 

UDP客户端和服务器端代码:


 

#coding=utf-8
#UDP 客户端代码

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

for data in ["chenshan","yuanhui","chendianqiang"]:
    s.sendto(data.encode(),(127.0.0.1,9999))
    print(s.recv(1024))
    
s.close()
#coding=utf-8
#UDP 协议服务器代码
import socket

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

s.bind((127.0.0.1,9999))
print("Bind UDP on prot:9999")

while True:
    data,addr=s.recvfrom(1024)
    print("Receive from %s:%s"% addr)
    s.sendto("Hello ".encode()+data,addr)

运行结果:

Bind UDP on prot:9999
bHello chenshan
bHello yuanhui
bHello chendianqiang

 

python 学习5 网络编程-TCP/UDP

标签:

原文地址:http://www.cnblogs.com/nzyjlr/p/4236287.html

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