Python製做一個簡單聊天室 -《狗嗨默示錄》-

client.pypython

# !/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import threading

outString = ''
inString = ''

def client_send(sock):
    global outString
    while True:
        #監聽輸入
        outString = input() #接收輸入
        outString = nick + ' : ' + outString
        sock.send(outString.encode('utf-8'))
def client_accept(sock):
    global inString
    while True:
        try:
            inString = sock.recv(1024).decode('utf-8') #接收數據
            if not inString:
                break
            if outString != inString:
                print(inString)
        except:
            break

nick = input('input your nickname:')
ip = input('input the server ip address:')
port = 8888
sock = socket.socket()#創建套接字
sock.connect((ip,port)) #鏈接

sock.send(nick.encode('utf-8'))

        
th_send = threading.Thread(target=client_send,args=(sock,))
th_send.start()
th_accept = threading.Thread(target=client_accept,args=(sock,))
th_accept.start()

 

server.pysocket

# !/usr/bin/env python
# -*- coding:utf-8 -*-

import socket
import threading

host = input('input the server ip address:')
port = 8888
data = '' #文本數據

s = socket.socket() #建立套接字
print('Socket created')
s.bind((host,port)) #綁定
s.listen(10) #監聽鏈接

print('Socket new listening')
cond = threading.Condition() #條件

def Notify_All(info):
    global data
    if cond.acquire(): #獲取
        data = info
        cond.notifyAll() #通知
        cond.release() #釋放
        

def ThreadOut(conn,nick): #發送消息
    global data
    while True:
        if cond.acquire():
            cond.wait() #等待
            if data:
                try:
                    conn.send(data.encode('utf-8'))
                    cond.release()
                except:
                    cond.release()
                    return

def ThreadIn(conn,nick): #接收消息
    global data
    while True:
        try:
            info = conn.recv(1024).decode('utf-8')
            if not info:
                conn.close()
                return
            Notify_All(info)
            print(data)
        except:
            Notify_All(nick + ' 掉線')
            print(data)
            return
            
            

while True:
    conn,addr = s.accept() #接受鏈接,addr包含ip,port
    print('Connected with '+addr[0]+' : '+str(addr[1]))
    nick = conn.recv(1024).decode('utf-8')
    welcome = 'Welcome '+ nick +' to the room(〃`▽`〃)'
    Notify_All(welcome)
    print(data)
    conn.send(data.encode('utf-8'))
    threading.Thread(target=ThreadOut,args=(conn,nick)).start()
    threading.Thread(target=ThreadIn,args=(conn,nick)).start()

 

相關文章
相關標籤/搜索