Python TCPSocket

2023-01-31 02:01:05 python TCPSocket

tcp套接字

TCPSockServer:

from Socket import *
from time import ctime
BUFFSISE = 1024
HOST = '127.0.0.1'
PORT = 10054
mySocket = socket(AF_INET, SOCK_STREAM, 0)
ADDR = (HOST, PORT)
mySocket.bind(ADDR)
mySocket.listen(5)
while True:
    print("waiting for connection...\n")
    clietSocket, clientAddr = mySocket.accept()
    print("recive an request from: ", clientAddr)
    while True:
        data = clietSocket.recv(BUFFSISE).decode()
        print("received data: %s" % data)
        if not data:
            break
        clietSocket.send(('[%s] %s' % (ctime(), data)).encode())
    clietSocket.close()
mySocket.close()

TCPSockClient:

from socket import *
HOST = '127.0.0.1'
PORT = 10054
ADDR = (HOST, PORT)
BUFFSIZE = 1024
mySocket = socket(AF_INET, SOCK_STREAM, 0)
mySocket.connect(ADDR)
while True:
    data = input(">: ")
    if not data:
        break
    mySocket.send(data.encode())
    data = mySocket.recv(BUFFSIZE)
    if not data:
        break
    print(data)
mySocket.close()

相关文章