TCP socket

3/8/2017来源:ASP.NET技巧人气:1649

import time
from socket import *

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

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

while True:
    PRint 'waiting for connection...'
    tcpCliSock, addr = tcpSerScok.accept()
    print '... connected from ', addr
    
    while True:
        data = tcpCliSock.recv(BUFSIZE)
        if not data:
            break
        tcpCliSock.send('[%s] %s'%(time.ctime(),  data))
        
    tcpCliSock.close()
        
tcpSerScok.close()

from socket import *

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

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

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