1. 程式人生 > >單程序伺服器-非堵塞模式

單程序伺服器-非堵塞模式

伺服器

#coding=utf-8
from socket import *
import time

# 用來儲存所有的新連結的socket
g_socketList = []

def main():
    serSocket = socket(AF_INET, SOCK_STREAM)
    serSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR , 1)
    localAddr = ('', 7788)
    serSocket.bind(localAddr)
    #可以適當修改listen中的值來看看不同的現象
    serSocket.listen(1000)
    #將套接字設定為非堵塞
    #設定為非堵塞後,如果accept時,恰巧沒有客戶端connect,那麼accept會
    #產生一個異常,所以需要try來進行處理
    serSocket.setblocking(False)

    while True:
        #用來測試
        #time.sleep(0.5)

        try:
            newClientInfo = serSocket.accept()
        except Exception as result:
            pass
        else:
            print("一個新的客戶端到來:%s"%str(newClientInfo))
            newClientInfo[0].setblocking(False)
            g_socketList.append(newClientInfo)

        # 用來儲存需要刪除的客戶端資訊
        needDelClientInfoList = []

        for clientSocket,clientAddr in g_socketList:
            try:
                recvData = clientSocket.recv(1024)
                if len(recvData)>0:
                    print('recv[%s]:%s'%(str(clientAddr), recvData))
                else:
                    print('[%s]客戶端已經關閉'%str(clientAddr))
                    clientSocket.close()
                    g_needDelClientInfoList.append((clientSocket,clientAddr))
            except Exception as result:
                pass
        for needDelClientInfo in needDelClientInfoList:
            g_socketList.remove(needDelClientInfo)

if __name__ == '__main__':
    main()

客戶端

#coding=utf-8
from socket import *
import random
import time

serverIp = raw_input("請輸入伺服器的ip:")
connNum = raw_input("請輸入要連結伺服器的次數(例如1000):")
g_socketList = []
for i in range(int(connNum)):
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((serverIp, 7788))
    g_socketList.append(s)
    print(i)

while True:
    for s in g_socketList:
        s.send(str(random.randint(0,100)))

    # 用來測試用
    #time.sleep(1)