Python Socket深度学习分享

简介: Python Socket深度学习分享

Server:

复制代码
import socket
port=8081
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

从指定的端口,从任何发送者,接收UDP数据

s.bind(('',port))
print('正在等待接入...')
while True:

#接收一个数据
data,addr=s.recvfrom(1024)
print('Received:',data,'from',addr)

复制代码
Client:

import socket
port=8081
host='localhost'
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto(b'hello,this is a test info !',(host,port))

很简单 。下面是TCP方式:

Server:

复制代码

-- coding: utf-8 --

from socket import *
from time import ctime

//代码效果参考:https://v.youku.com/v_show/id_XNjQwNjgzODMwNA==.html

HOST=''
PORT=12345
BUFSIZ=1024
ADDR=(HOST, PORT)
sock=socket(AF_INET, SOCK_STREAM)

sock.bind(ADDR)

sock.listen(5)
while True:
print('waiting for connection')
tcpClientSock, addr=sock.accept()
print('connect from ', addr)
while True:
try:
data=tcpClientSock.recv(BUFSIZ)
except:
print(e)
tcpClientSock.close()
break
if not data:
break
s='Hi,you send me :[%s] %s' %(ctime(), data.decode('utf8'))
tcpClientSock.send(s.encode('utf8'))
print([ctime()], ':', data.decode('utf8'))
tcpClientSock.close()
sock.close()
复制代码
Client:

复制代码

-- coding: utf-8 --

from socket import *

class TcpClient:
HOST='127.0.0.1'
PORT=12345
BUFSIZ=1024
ADDR=(HOST, PORT)
def init(self):
self.client=socket(AF_INET, SOCK_STREAM)
self.client.connect(self.ADDR)

    while True:
        data=input('>')
        if not data:
            break
        self.client.send(data.encode('utf8'))
        data=self.client.recv(self.BUFSIZ)
        if not data:
            break
        print(data.decode('utf8'))

//代码效果参考:https://v.youku.com/v_show/id_XNjQwNjg0MTE5Mg==.html

if name == 'main':
client=TcpClient()
复制代码
上面的TCP方式有个问题,不能退出,好吧,我们改造一下,使这个程序可以发送quit命令以退出:

Server:

复制代码

-- coding: utf-8 --

from socket import *
from time import ctime
from time import localtime
import time

HOST=''
PORT=1122 #设置侦听端口
BUFSIZ=1024
ADDR=(HOST, PORT)
sock=socket(AF_INET, SOCK_STREAM)

sock.bind(ADDR)

sock.listen(5)

设置退出条件

STOP_CHAT=False
while not STOP_CHAT:
print('等待接入,侦听端口:%d' % (PORT))
tcpClientSock, addr=sock.accept()
print('接受连接,客户端地址:',addr)
while True:
try:
data=tcpClientSock.recv(BUFSIZ)
except:

        #print(e)
        tcpClientSock.close()
        break
    if not data:
        break
    #python3使用bytes,所以要进行编码
    #s='%s发送给我的信息是:[%s] %s' %(addr[0],ctime(), data.decode('utf8'))
    #对日期进行一下格式化
    ISOTIMEFORMAT='%Y-%m-%d %X'
    stime=time.strftime(ISOTIMEFORMAT, localtime())
    s='%s发送给我的信息是:%s' %(addr[0],data.decode('utf8'))
    tcpClientSock.send(s.encode('utf8'))
    print([stime], ':', data.decode('utf8'))
    #如果输入quit(忽略大小写),则程序退出
    STOP_CHAT=(data.decode('utf8').upper()=="QUIT")
    if STOP_CHAT:
        break

tcpClientSock.close()
sock.close()
复制代码
Client:

相关文章
|
监控 Shell Linux
【Shell 命令集合 系统管理 】Linux 自动轮转(log rotation)日志文件 logrotate命令 使用指南
【Shell 命令集合 系统管理 】Linux 自动轮转(log rotation)日志文件 logrotate命令 使用指南
461 0
|
10月前
|
安全 Go 调度
Go语言中的并发编程:掌握goroutines和channels
在现代软件开发中,并发编程已经成为不可或缺的一部分。Go语言以其简洁的语法和强大的并发特性,成为了开发者的首选之一。本文将深入探讨Go语言中的两个核心概念——goroutines和channels,并通过实际代码示例展示如何使用它们来实现高效的并发处理。无论你是初学者还是有经验的开发者,通过本文的学习,你将能够更好地理解和应用Go语言的并发机制,提升你的编程技能。
|
Linux
linux如何去掉目录背景颜色
linux如何去掉目录背景颜色
346 2
|
10月前
|
JSON JavaScript 前端开发
|
10月前
|
传感器 监控 物联网
新技术趋势与应用:探讨新兴技术如物联网、虚拟现实等的发展趋势和应用场景###
本文探讨了物联网(IoT)与虚拟现实(VR)这两项新兴技术的快速发展及其在多个领域的应用场景。物联网通过设备互联、数据驱动和应用场景拓展,正在智能家居、智慧城市、工业自动化等方面带来革命性变化。虚拟现实则以其沉浸式体验和不断增强的交互性,在游戏娱乐、教育培训、医疗健康等领域展现出巨大潜力。结合具体案例分析,本文揭示了这些技术如何独立演进又相互融合,共同推动社会进步,并展望未来可能带来的变革。 ###
|
前端开发 Java Maven
Maven 快照(SNAPSHOT)
**Maven SNAPSHOT简化多团队协作:**当开发中的data-service频繁更新时,使用1.0-SNAPSHOT标识,每次构建Maven自动检查远程仓库的最新快照,避免了手动通知和更新pom.xml的繁琐步骤,促进模块间的无缝集成。
|
开发工具 存储 开发者
Xamarin 与 Azure 竟然无缝集成,数据存储、身份验证、人工智能全涵盖,开启移动应用开发新境界!
【8月更文挑战第31天】Xamarin 是一款强大的跨平台移动应用开发工具,支持使用 C# 同时为 iOS、Android 和 Windows 开发应用。结合 Azure 云服务平台,Xamarin 能够提供数据存储、身份验证及人工智能等多种服务。示例代码展示了如何在 Xamarin.Forms 中使用 Entity Framework Core 连接 Azure SQL Database,并利用 Azure Active Directory 实现安全认证。这种集成让开发者能够构建出高效且功能丰富的移动应用。
74 0
|
移动开发 小程序 JavaScript
uView Input 输入框
uView Input 输入框
231 0
|
Linux API
Linux网络编程(多路IO复用poll)
Linux网络编程(多路IO复用poll)
163 0
|
消息中间件 存储 网络协议
深入了解ActiveMQ!
深入了解ActiveMQ!
955 0

热门文章

最新文章