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

Python编程之socket

时间:2018-12-14 23:03:48      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:消息   log   编程   rip   python   int   continue   strip   break   

1、TCP

客户端:

from socket import *
ip_port = ("127.0.0.1",8888)
back_log = 5
buffer_size = 1024
tcp_client = socket(AF_INET,SOCK_STREAM)
tcp_client.connect(ip_port)
while 1:
    msg = input(">>>>>>>:").strip()
    if not msg:continue
    tcp_client.send(msg.encode("utf-8"))
    print("客户端已发送消息",msg)
    data = tcp_client.recv(buffer_size)
    print("客户端收到的数据是",data.decode("utf-8"))
tcp_client.close()

服务端:

from socket import *
ip_port = ("127.0.0.1",8888)
back_log = 5
buffer_size = 1024
tcp_server = socket(AF_INET,SOCK_STREAM)
tcp_server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)#解决服务端断开延时问题
tcp_server.bind(ip_port)
tcp_server.listen(back_log)
print("服务端开始运行了")
while 1:
    conn,adr = tcp_server.accept()#服务端阻塞
    print("双向连接是",conn)
    print("客户端地址是",adr)
    while 1:
        try:
            data = conn.recv(buffer_size)
            print("客户端发来的消息是",data.decode("utf-8"))
            conn.send(data.upper())
            print("服务端回复的消息是",data.upper(),"客户端消息回复成功")
        except Exception:
            break
    conn.close()
tcp_server.close()

 

Python编程之socket

标签:消息   log   编程   rip   python   int   continue   strip   break   

原文地址:https://www.cnblogs.com/huoyunxieshen/p/10121772.html

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