例項 Python實現聊天室

2022-05-06 12:00:11 字數 2727 閱讀 8000

廢話不多說,直接上**

服務端:

import socket

from threading import thread

client_dict = {}

def brodcast(msg,nikename = ''):

for khd_socket in client_dict.values():

khd_socket.send(bytes(nikename.encode('gbk') + msg + b'\n'))

def chat(khd_socket:socket.socket):

try:

nikename = khd_socket.recv(1024).decode('gbk')

welcome = f'歡迎加入聊天室\n'

client_dict[nikename] = khd_socket

brodcast(welcome.encode('gbk'))

while true:

try:

msg = khd_socket.recv(1024)

brodcast(msg,nikename + ':')

except:

khd_socket.close()

del client_dict[nikename]

brodcast(bytes(f'離開聊天室\n','gbk'))

except:

print('客戶端斷開連線')

if __name__ == '__main__':

tcp = socket.socket(socket.af_inet,socket.sock_stream)

tcp.setsockopt(socket.sol_socket,socket.so_reuseaddr,true)

tcp.bind(("",9090))

print(f'伺服器已開啟,正在等待使用者進入...')

tcp.listen(127)

while true:

try:

khd_socket, ip = tcp.accept()

print(f'建立連線')

khd_socket.send('歡迎加入聊天室,輸入暱稱開始聊天\n'.encode('gbk'))

khd_thread = thread(target=chat,args=(khd_socket,))

khd_thread.daemon = true

khd_thread.start()

except:

print('客戶端斷開連線')

tcp.close()

客戶端(gui):

import socket

from tkinter import tk, frame, text, button, end

from threading import thread

windows = tk()

windows.title('聊天室')

message_frame = frame(width=480,height=300,bg='white')

text_frame = frame(width=480,height=100)

send_frame = frame(width=480,height=30)

tcp = socket.socket(socket.af_inet,socket.sock_stream)

tcp.connect(('127.0.0.1',9090))

def get_msg():

while true:

try:

msg = tcp.recv(1024)

text_message.insert(end,msg.decode('gbk'))

except:

break

def send():

send_msg = text_text.get('0.0',end)

if send_msg.endswith('\n'):

send_msg = send_msg[:-1]

tcp.send(send_msg.encode('gbk'))

text_text.delete('0.0',end)

text_message = text(message_frame)

text_text = text(text_frame)

button_send = button(send_frame,text='傳送',command=send)

message_frame.grid(row=0,column=0,padx=3,pady=6)

text_frame.grid(row=1,column=0,padx=3,pady=6)

send_frame.grid(row=2,column=0)

message_frame.grid_propagate(0)

text_frame.grid_propagate(0)

send_frame.grid_propagate(0)

text_message.grid()

text_text.grid()

button_send.grid()

msg_thread = thread(target=get_msg)

msg_thread.start()

windows.mainloop()

Python之實現聊天室

from socket import import threading s1 socket af inet,sock dgram localhost 192.168.2.216 8077 otherhost 192.168.2.216 8088 s1.bind localhost defmain p...

php html實現聊天室

1.最簡單的方式 不斷重新整理頁面 資料庫建立 create table chat chattime datetime,nick char 10 words char 150 login.php 請輸入您的暱稱 cdisplay.php conn mysql connect 127.0.0.1 ro...

mysql 聊天室 聊天室php mysql 六

聊天室php mysql 六 相應的 資料庫 phpmyadmin mysql dump 主機 localhost 3306 資料庫 study28 資料表的結構 chat user create table chat user userid varchar 20 not null,passwd v...