Python的socket编程
当前位置:以往代写 > Python教程 >Python的socket编程
2019-06-14

Python的socket编程

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

    关键字:

在线提交作业