1. 程式人生 > >python socket程式設計

python socket程式設計

#客戶端
# -*-coding: utf-8 -*-
import socket
import threading
outString = ''
inString = ''
nick =''
#傳送資訊
def DealOut(sock):
    global nick,outString
    while True:
        outString = input()
        outString = nick + ':'+outString
        print (outString)
        sock.send(outString.encode())
def
DealIn(sock):
global inString while True: try: inString = sock.recv(1024).decode() if not inString: break if outString != inString: #自己發的 print(inString) except: break #ip = raw_input("input the server ip address:")
ip='127.0.0.1' sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((ip,8887)) while 1: nick = input("input your nickname:") pword = input("input your password:") print(nick) print(pword) sock.send((nick+' '+pword).encode()) judge = sock.recv(1024).decode() print(judge) if
judge == "1": print("成功登入") break else : print("使用者名稱或密碼錯啦。再試一次吧") thin = threading.Thread(target=DealIn,args=(sock,)) #接受資訊 thin.start() thout = threading.Thread(target=DealOut,args=(sock,)) #傳送資訊 thout.start()
#服務端
# -*-coding: utf-8 -*-
import socket
import threading

user = [('liu_jiangwen','1234'),('2222','2345')]


#接受客戶端發來的資訊
def clientThreadIn(conn,nick):
    global  data
    while True:
        try:
            tmp = conn.recv(1024).decode()
            if not tmp:
                conn.close()
                return
            NotifyAll(tmp)
            print(data)

        except :
            NotifyAll(nick+'leaves the room') #出現異常推出
            print(data)
            return
def clientThreadOut(conn,nick):
    global data
    while True:
        if con.acquire():
            con.wait()  #放棄對資源佔用,等待通知 ,然後執行後面程式碼
            if data:
                try:
                    conn.send(data.encode())
                    con.release()
                except:
                    con.release()
                    return




def NotifyAll(ss):
    global  data
    if con.acquire(): #獲取鎖 鎖定執行緒所有權
        data = ss
        con.notifyAll() #放棄當前執行緒對資源的佔用,通知所有等待執行緒從wait方法執行
        con.release()



#HOST = raw_input("input the server ip address:")
con = threading.Condition()
HOST = '127.0.0.1'
port = 8887
data = ''

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('socket created')
s.bind((HOST,port))
s.listen(5)
print('Socket now listening')


while True:
    conn,addr = s.accept() #接受連線
    print('Connected with'+addr[0]+':'+str(addr[1]))
    while 1:
        infor = conn.recv(1024).decode() #獲取使用者名稱
        print(infor)
        infor = infor.split()
        nick,pword = infor[0],infor[1]

        if (nick,pword) not in user:
            conn.send("0".encode())
        else:
            conn.send("1".encode())
            break
    NotifyAll('Welcome'+str(nick)+'to the room!')
    print(data)
    print(  str((threading.activeCount()+1)/2) + 'person(s)' ) #當前房間人數 兩個執行緒/2
    conn.send(data.encode())
    threading.Thread(target=clientThreadIn, args=(conn, nick)).start()
    threading.Thread(target=clientThreadOut, args=(conn, nick)).start()