Python:socketプログラミング、TCP/UDP

2153 ワード

一、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章ネットワークプログラミング.