Python:socket编程,TCP/UDP

一、TCP客户端/服务端

1.1 tcpSrv.py

#!/usr/bin/env python

from socket import *
from time import ctime

HOST = ""
PORT = 6000
BUFSIZE = 1024
ADDR = (HOST, PORT)

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

while True:
        sockCli,addr = sockSrv.accept()
        print "...connected from:", addr
        while True:
                data = sockCli.recv(BUFSIZE)
                if not data:
                        break
                print data;
                sockCli.send("[%s] %s" % (ctime(), data))
        sockCli.close()

sockSrv.close()

1.2 tcpCli.py

[root@localhost python]# vim tcpCli.py 
#!/usr/bin/env python

from socket import *

HOST = "localhost"
PORT = 6000
BUFSIZE = 1024
ADDR = (HOST, PORT)

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

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

sockCli.close()

二、UDP客户端/服务端

2.1 udpSrv.py

#!/usr/bin/env python

from socket import *
from time import ctime

HOST = ""
PORT = 6000
BUFSIZE = 1024
ADDR = (HOST, PORT)

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

while True:
        data, addr = sockSrv.recvfrom(BUFSIZE)
        print "receive %s from %s" % (data, addr)
        sockSrv.sendto("[%s] %s"%(ctime(),data), addr)


sockSrv.close()

2.2 udpCli.py

#!/usr/bin/env python

from socket import *

HOST = "localhost"
PORT = 6000
BUFSIZE = 1024
ADDR = (HOST, PORT)

sockCli = socket(AF_INET, SOCK_DGRAM)

while True:
        data = raw_input(">")
        if not data:
                break
        sockCli.sendto(data, ADDR)
        data, addr = sockCli.recvfrom(BUFSIZE)
        if not data:
                break
        print data


sockCli.close()


参考资料:

      《Python核心编程》:第16章 网络编程。



你可能感兴趣的:(Python:socket编程,TCP/UDP)