当前位置:编程学习 > python >>

Python最简单socket程序

服务器程序:
#!/usr/bin/python
# Filename: server.py
# Author: kevin Sun

import socket
import time

PORT = 8088
BUFSIZE = 1024
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

tcpSocket.bind(('', PORT))

tcpSocket.listen(5)

while True:
    print "Waiting for connection..."
   
    tcpClient, addr = tcpSocket.accept()
   
    print '...connected from:', addr
   
    while True:
        data = tcpClient.recv(BUFSIZE)
       
        if not data:
            break
   
        tcpClient.send('[%s] %s' % (time.ctime(), data))

tcpSocket.close()
tcpClient.close()

客户端:
#!/usr/bin/python
# Filename: client.py
# Author: Kevin Sun

import socket

PORT = 8088
BUFSIZE = 1024

clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

clientSocket.connect(('localhost', PORT))

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

补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,