tcp网络编程用户登陆
时间: 2024-01-12 19:22:18 浏览: 26
以下是一个使用Qt中的TCP客户端编程实现用户登录的示例:
```python
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton
from PyQt5.QtNetwork import QTcpSocket
class LoginWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("用户登录")
self.resize(300, 200)
layout = QVBoxLayout()
self.label_username = QLabel("用户名:")
self.edit_username = QLineEdit()
layout.addWidget(self.label_username)
layout.addWidget(self.edit_username)
self.label_password = QLabel("密码:")
self.edit_password = QLineEdit()
self.edit_password.setEchoMode(QLineEdit.Password)
layout.addWidget(self.label_password)
layout.addWidget(self.edit_password)
self.button_login = QPushButton("登录")
self.button_login.clicked.connect(self.login)
layout.addWidget(self.button_login)
self.setLayout(layout)
self.tcp_socket = QTcpSocket()
self.tcp_socket.connected.connect(self.on_connected)
self.tcp_socket.disconnected.connect(self.on_disconnected)
self.tcp_socket.readyRead.connect(self.on_ready_read)
def login(self):
username = self.edit_username.text()
password = self.edit_password.text()
if username and password:
self.tcp_socket.connectToHost("服务器IP地址", 8888)
# 发送登录请求数据
self.tcp_socket.write(f"LOGIN|{username}|{password}".encode())
def on_connected(self):
print("已连接到服务器")
def on_disconnected(self):
print("与服务器断开连接")
def on_ready_read(self):
data = self.tcp_socket.readAll().data().decode()
if data == "LOGIN_SUCCESS":
print("登录成功")
elif data == "LOGIN_FAILED":
print("登录失败")
if __name__ == "__main__":
app = QApplication(sys.argv)
login_window = LoginWindow()
login_window.show()
sys.exit(app.exec_())
```
请注意,上述示例中的服务器IP地址和端口号需要根据实际情况进行修改。