-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverGUI.py
More file actions
105 lines (83 loc) · 2.48 KB
/
serverGUI.py
File metadata and controls
105 lines (83 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import socket
from _thread import start_new_thread
import threading
import platform
from PySide6.QtWidgets import (
QApplication
, QMessageBox
, QWidget
, QLabel
, QPushButton
, QVBoxLayout
, QPlainTextEdit
)
list_of_clients = []
def clientthread(conn, addr):
# sends a message to the client whose user object is conn
conn.send(bytes("Welcome to this chatroom!\n", "utf-8"))
while True:
try:
message = str(conn.recv(2048), "utf-8")
print("<" + str(addr[0]) + "> " + str(message))
# Calls broadcast function to send message to all
message_to_send = "<" + str(addr[0]) + "> " + str(message)
broadcast(message_to_send, conn)
except:
continue
def broadcast(message, connection):
for clients in list_of_clients:
if clients != connection:
try:
clients.send(bytes(message, "utf-8"))
except:
print("closing Client", clients)
clients.close()
remove(clients)
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
app = QApplication([])
app.setStyle(platform.system().lower())
window = QWidget()
v_layout = QVBoxLayout()
connect = QPushButton('connect')
IP = QPlainTextEdit("localhost")
IP.setMaximumSize(100, 25)
IP.setMinimumSize(100, 25)
port = QPlainTextEdit("port")
port.setMaximumSize(100, 25)
port.setMinimumSize(100, 25)
v_layout.addWidget(QLabel('IP and Port'))
v_layout.addWidget(IP)
v_layout.addWidget(port)
v_layout.addWidget(connect)
#button "connect" connects AND disconnects the server
disconn = False
def on_btn1_clicked():
global disconn
if disconn:
# conn.close()
server.close()
return
server.bind((IP.toPlainText(), int(port.toPlainText())))
server.listen(100)
connect.setText('disconnect')
disconn = True
alert = QMessageBox()
alert.setText('Connected')
alert.exec()
def whileLoop():
global list_of_clients
while True:
conn, addr = server.accept()
list_of_clients.append(conn)
print(addr[0] + " connected")
start_new_thread(clientthread, (conn, addr))
t1 = threading.Thread(target=whileLoop)
t1.start()
connect.clicked.connect(on_btn1_clicked)
window.setLayout(v_layout)
window.show()
app.exec()