返回顶部

收藏

Python的socket编程

更多

目前处在学习python的阶段,昨天看到了python的socket模块,分别实现TCP、UDP时间戳回显。 1、tcp通信server和client代码

# tcpServer.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

from socket import *
from time import ctime

HOST = ''
PORT = 21156
BUFSIZE = 1024
ADDR = (HOST,PORT)

tcpServerSock = socket(AF_INET,SOCK_STREAM)
tcpServerSock.bind(ADDR)
tcpServerSock.listen(5)

while True:
    print 'waiting for connection...'
    tcpClientSock ,addr = tcpServerSock.accept()
    print '...connected from:',addr

    while True:
        data=tcpClientSock.recv(BUFSIZE)
        if not data:
            break
        tcpClientSock.send('[%s] %s' % (ctime(),data))

        tcpClientSock.close()
tcpServerSock.close
``````python
# tcpClient.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

from socket import *

HOST = 'localhost'
PORT = 21156
BUFSIZE = 1024
ADDR = (HOST,PORT)

tcpClientSock = socket(AF_INET,SOCK_STREAM)
tcpClientSock.connect(ADDR)

while True:
    data = raw_input('>')
    if not data:
        break
    tcpClientSock.send(data)
    data = tcpClientSock.recv(BUFSIZE)
    if not data:
        break
    print data

tcpClientSock.close()

2、udp通信server和client代码

#udpServer.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

from socket import *
from time import ctime

HOST = ''
PORT = 21156
BUFSIZE = 1024
ADDR = (HOST,PORT)

udpServerSock = socket(AF_INET,SOCK_DGRAM)
udpServerSock.bind(ADDR)

while True:
    print 'waiting for message...'
    data ,addr = udpServerSock.recvfrom(BUFSIZE)
    udpServerSock.sendto('[%s] %s' % (ctime(),data), addr)
    print '...received from and returned to:',addr

        tcpClientSock.close()
tcpServerSock.close
``````python
#udpClient.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

from socket import *
# from time import ctime

HOST = 'localhost'
PORT = 21156
BUFSIZE = 1024
ADDR = (HOST,PORT)

udpClientSock = socket(AF_INET,SOCK_DGRAM)

while True:
    data = raw_input('>')
    if not data:
        break
    udpClientSock.sendto(data,ADDR)
    data,ADDR = udpClientSock.recvfrom(BUFSIZE)
    if not data:
        break
    print data

udpClientSock.close()

标签:python

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 课程图谱 发表 2017-12-10 12:52:59 Coursera上Python课程(公开课)汇总推荐:从Python入门到应用Python
  2. 博主 发表 2017-12-10 08:02:50 使用有限状态机原理实现英文分词
  3. 博主 发表 2017-12-10 06:21:33 Python 爬虫实战(一):使用 requests 和 BeautifulSoup
  4. shonenada 发表 2013-04-30 04:17:00 Python Learning Notes
  5. shonenada 发表 2013-07-18 17:20:00 think-python_0
  6. shonenada 发表 2013-07-18 17:23:00 think-python_1
  7. shonenada 发表 2013-07-18 17:24:00 "think-python_2"
  8. shonenada 发表 2014-02-01 05:55:00 pip's Trap
  9. shonenada 发表 2014-02-09 16:19:00 flask-rbac
  10. shonenada 发表 2016-04-29 16:00:00 说一说 R2D2
  11. ksc 发表 2014-03-11 05:47:04 给树莓派添加重启关机按钮
  12. ksc 发表 2014-02-13 11:47:37 python argparse模块bug:将版本信息输出到标准错误

发表评论