找了N久,终于找到一个真正可用的socket连接代码。辛苦。

稳定可靠的Socket聊天室实现

找了N久,终于找到一个真正可用的socket连接代码,而且通讯不像网上那些,通讯一次后就无法再通讯了。

辛苦。^_^ 

 

namespace WindowsApplication3
{
    partial class Form1
    {
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox textBox3;
        private System.Windows.Forms.TextBox textBox4;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.StatusBar statusBar1;
        private System.Windows.Forms.GroupBox groupBox4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.TextBox textBox5;
        private System.Windows.Forms.TextBox textBox6;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Button button4;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.RichTextBox richTextBox2;
        private System.Windows.Forms.Button button5;
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.textBox4 = new System.Windows.Forms.TextBox();
            this.button2 = new System.Windows.Forms.Button();
            this.label4 = new System.Windows.Forms.Label();
            this.button3 = new System.Windows.Forms.Button();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.textBox6 = new System.Windows.Forms.TextBox();
            this.label6 = new System.Windows.Forms.Label();
            this.button5 = new System.Windows.Forms.Button();
            this.label5 = new System.Windows.Forms.Label();
            this.textBox5 = new System.Windows.Forms.TextBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.statusBar1 = new System.Windows.Forms.StatusBar();
            this.groupBox4 = new System.Windows.Forms.GroupBox();
            this.button4 = new System.Windows.Forms.Button();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.richTextBox2 = new System.Windows.Forms.RichTextBox();
            this.groupBox5 = new System.Windows.Forms.GroupBox();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox4.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.groupBox5.SuspendLayout();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label1.Location = new System.Drawing.Point(8, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(64, 23);
            this.label1.TabIndex = 0;
            this.label1.Text = "主机名称:";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(80, 16);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(40, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "获取";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(8, 48);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(112, 21);
            this.textBox1.TabIndex = 2;
            //
            // label2
            //
            this.label2.Location = new System.Drawing.Point(8, 72);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(64, 23);
            this.label2.TabIndex = 0;
            this.label2.Text = "IP地址:";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(8, 96);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(112, 21);
            this.textBox2.TabIndex = 2;
            //
            // label3
            //
            this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.label3.Location = new System.Drawing.Point(80, 112);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(64, 23);
            this.label3.TabIndex = 3;
            this.label3.Text = "我的妮称:";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // textBox3
            //
            this.textBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.textBox3.Location = new System.Drawing.Point(136, 112);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(128, 21);
            this.textBox3.TabIndex = 4;
            //
            // textBox4
            //
            this.textBox4.Location = new System.Drawing.Point(8, 48);
            this.textBox4.Name = "textBox4";
            this.textBox4.Size = new System.Drawing.Size(120, 21);
            this.textBox4.TabIndex = 5;
            this.textBox4.Text = "127.0.0.1";
            //
            // button2
            //
            this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.button2.Location = new System.Drawing.Point(272, 112);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(72, 23);
            this.button2.TabIndex = 6;
            this.button2.Text = "发送";
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // label4
            //
            this.label4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label4.Location = new System.Drawing.Point(8, 16);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(120, 23);
            this.label4.TabIndex = 7;
            this.label4.Text = "服务器IP:";
            this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // button3
            //
            this.button3.Location = new System.Drawing.Point(8, 48);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(64, 23);
            this.button3.TabIndex = 8;
            this.button3.Text = "开始监听";
            this.button3.Click += new System.EventHandler(this.button3_Click);
            //
            // richTextBox1
            //
            this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.richTextBox1.Location = new System.Drawing.Point(8, 16);
            this.richTextBox1.MaxLength = 1000;
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(336, 88);
            this.richTextBox1.TabIndex = 11;
            this.richTextBox1.Text = "";
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.textBox6);
            this.groupBox1.Controls.Add(this.textBox4);
            this.groupBox1.Controls.Add(this.label4);
            this.groupBox1.Controls.Add(this.label6);
            this.groupBox1.Controls.Add(this.button5);
            this.groupBox1.Location = new System.Drawing.Point(368, 8);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(136, 152);
            this.groupBox1.TabIndex = 13;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "连接服务器";
            //
            // textBox6
            //
            this.textBox6.Location = new System.Drawing.Point(80, 80);
            this.textBox6.Name = "textBox6";
            this.textBox6.Size = new System.Drawing.Size(48, 21);
            this.textBox6.TabIndex = 5;
            //
            // label6
            //
            this.label6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label6.Location = new System.Drawing.Point(8, 80);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(64, 23);
            this.label6.TabIndex = 7;
            this.label6.Text = "目标端口:";
            this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // button5
            //
            this.button5.Location = new System.Drawing.Point(8, 120);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(64, 23);
            this.button5.TabIndex = 8;
            this.button5.Text = "请求连接";
            this.button5.Click += new System.EventHandler(this.button5_Click);
            //
            // label5
            //
            this.label5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label5.Location = new System.Drawing.Point(8, 16);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(64, 23);
            this.label5.TabIndex = 7;
            this.label5.Text = "监听端口:";
            this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // textBox5
            //
            this.textBox5.Location = new System.Drawing.Point(80, 16);
            this.textBox5.Name = "textBox5";
            this.textBox5.Size = new System.Drawing.Size(48, 21);
            this.textBox5.TabIndex = 5;
            //
            // groupBox2
            //
            this.groupBox2.Controls.Add(this.textBox1);
            this.groupBox2.Controls.Add(this.textBox2);
            this.groupBox2.Controls.Add(this.label1);
            this.groupBox2.Controls.Add(this.button1);
            this.groupBox2.Controls.Add(this.label2);
            this.groupBox2.Location = new System.Drawing.Point(368, 288);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(136, 128);
            this.groupBox2.TabIndex = 14;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "本机IP";
            //
            // statusBar1
            //
            this.statusBar1.Location = new System.Drawing.Point(0, 422);
            this.statusBar1.Name = "statusBar1";
            this.statusBar1.Size = new System.Drawing.Size(512, 16);
            this.statusBar1.TabIndex = 15;
            this.statusBar1.TextChanged += new System.EventHandler(this.statusBar1_TextChanged);
            //
            // groupBox4
            //
            this.groupBox4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox4.Controls.Add(this.textBox3);
            this.groupBox4.Controls.Add(this.button4);
            this.groupBox4.Controls.Add(this.richTextBox1);
            this.groupBox4.Controls.Add(this.label3);
            this.groupBox4.Controls.Add(this.button2);
            this.groupBox4.Location = new System.Drawing.Point(8, 272);
            this.groupBox4.Name = "groupBox4";
            this.groupBox4.Size = new System.Drawing.Size(352, 144);
            this.groupBox4.TabIndex = 17;
            this.groupBox4.TabStop = false;
            this.groupBox4.Text = "发送窗口";
            //
            // button4
            //
            this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.button4.Location = new System.Drawing.Point(8, 112);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(64, 23);
            this.button4.TabIndex = 12;
            this.button4.Text = "清空消息";
            this.button4.Click += new System.EventHandler(this.button4_Click);
            //
            // groupBox3
            //
            this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox3.Controls.Add(this.richTextBox2);
            this.groupBox3.Location = new System.Drawing.Point(8, 8);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(352, 264);
            this.groupBox3.TabIndex = 18;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "聊天记录";
            //
            // richTextBox2
            //
            this.richTextBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.richTextBox2.Location = new System.Drawing.Point(8, 16);
            this.richTextBox2.Name = "richTextBox2";
            this.richTextBox2.Size = new System.Drawing.Size(336, 240);
            this.richTextBox2.TabIndex = 0;
            this.richTextBox2.Text = "";
            //
            // groupBox5
            //
            this.groupBox5.Controls.Add(this.label5);
            this.groupBox5.Controls.Add(this.textBox5);
            this.groupBox5.Controls.Add(this.button3);
            this.groupBox5.Location = new System.Drawing.Point(368, 184);
            this.groupBox5.Name = "groupBox5";
            this.groupBox5.Size = new System.Drawing.Size(136, 80);
            this.groupBox5.TabIndex = 19;
            this.groupBox5.TabStop = false;
            this.groupBox5.Text = "监听设置";
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(512, 438);
            this.Controls.Add(this.groupBox5);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox4);
            this.Controls.Add(this.statusBar1);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.groupBox2);
            this.MaximumSize = new System.Drawing.Size(520, 472);
            this.MinimumSize = new System.Drawing.Size(520, 472);
            this.Name = "Form1";
            this.Text = "点对点聊天";
            this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.groupBox4.ResumeLayout(false);
            this.groupBox4.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.groupBox5.ResumeLayout(false);
            this.groupBox5.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion


  
    }
}

 

 

 

 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Text;

namespace WindowsApplication3
{
    public partial class Form1 : Form
    {

        private Thread listenthread;//表示监听的线程
        private string msg; //要发送的消息
        private Socket socket1; //Socket类用于接收和发送信息       
        private IPEndPoint lep;
        private System.Windows.Forms.GroupBox groupBox5; //请求连接的节点


        public Form1()
        {
            InitializeComponent();
        }
        private void listenstart()//监听发入的信息
        {
            try
            {

                while (this.socket1.Connected)
                {
                    //设置一个缓冲区
                    Byte[] stream = new Byte[1024];
                    socket1.Receive(stream);
                    //将获得的流转化为字符串类型
                    string message = Encoding.Default.GetString(stream);
                    //this.textBox1.Text=socket1.Available.ToString();
                    this.richTextBox2.AppendText(message);
                    this.richTextBox2.AppendText(" ");
                }
            }
            catch//(Exception error)
            {
                if (!this.socket1.Connected)
                {
                    socket1.Close();
                    button3.Enabled = true;
                    button5.Enabled = true;
                }
            }
        }
        private void button1_Click(object sender, System.EventArgs e)
        {
            //获取本地主机名称
            string host = Dns.GetHostName();
            this.textBox1.Text = host;

            //获取本机IP
            IPAddress[] addrs = Dns.Resolve("localhost").AddressList;
            IPAddress addr = Dns.Resolve(host).AddressList[0];
            //转化为标准的以点分隔的四部分格式
            this.textBox2.Text = addr.ToString();
        }

        private void button3_Click(object sender, System.EventArgs e)
        {
            //获得监听端口
            int hostport;
            try
            {
                hostport = Int32.Parse(this.textBox5.Text);
                if (hostport < 135 || hostport > 65400) hostport = 12800;
            }
            catch
            {
                hostport = 12800;
            }
            //IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            lep = new IPEndPoint(ipAddress, hostport);
            socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket1.Bind(lep);
                socket1.Listen(10000);
                this.statusBar1.Text = "等待连接...";
                button3.Enabled = false;
                button5.Enabled = false;
                Thread watt = new Thread(new ThreadStart(waits));
                watt.Start();

            }
            catch
            {
                button3.Enabled = true;
            }

        }
        private void waits()
        {
            try
            {
                socket1 = socket1.Accept();
                this.statusBar1.Text = "已建立连接";
                listenthread = new Thread(new ThreadStart(listenstart));
                listenthread.Start();
                button3.Enabled = false;
                button5.Enabled = false;
            }
            catch
            {
                button3.Enabled = true;
                button5.Enabled = true;

            }

        }

        private void statusBar1_TextChanged(object sender, System.EventArgs e)
        {

        }

        private void button2_Click(object sender, System.EventArgs e)
        {
            if (socket1.Connected)
            {
                //将发送的字符串转换成字节数组
                msg = "<" + this.textBox3.Text + ">" + this.richTextBox1.Text;
                Byte[] bytes = Encoding.Default.GetBytes(msg);
                //发送数组
                try
                {
                    socket1.Send(bytes, bytes.Length, SocketFlags.None);
                    this.richTextBox1.Text = "";
                }
                catch
                {
                }
                //this.richTextBox2.AppendText(msg);
            }
        }

 

        private void button4_Click(object sender, System.EventArgs e)
        {
            this.richTextBox2.Text = "";
        }

        private void button5_Click(object sender, System.EventArgs e)
        {
            //获得连接端口
            int hostport;
            try
            {
                hostport = Int32.Parse(this.textBox6.Text);
                if (hostport < 135 || hostport > 65400) hostport = 12800;
            }
            catch
            {
                hostport = 12800;
            }

            try
            {
                //得到需连接的地址
                lep = new IPEndPoint(IPAddress.Parse(this.textBox4.Text), hostport);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
            //构造socket1实例,并请求连接
            socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket1.Connect(lep);
                if (socket1.Connected) this.statusBar1.Text = "连接成功";
                //开始监听
                listenthread = new Thread(new ThreadStart(listenstart));
                listenthread.Start();
                button5.Enabled = false;
                button3.Enabled = false;
            }
            catch
            {
                button5.Enabled = true;
                button3.Enabled = true;
            }
        }

        private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                socket1.Close();
                if (this.listenthread != null)
                {
                    //如果线程还处于运行状态就关闭它
                    if (this.listenthread.ThreadState == ThreadState.Running)
                    {
                        this.listenthread.Abort();
                    }
                }
            }
            catch
            {
            }

        }

    }
}

import sys import os import socket import pymysql from PySide2.QtWidgets import QApplication, QMessageBox, QWidget, QVBoxLayout, QLabel, QPushButton from PySide2.QtCore import Qt # ========== 动态资源路径 & 插件设置 ========== def resource_path(relative_path): """ 获取资源的绝对路径,兼容 PyInstaller 打包 """ try: base_path = sys._MEIPASS except Exception: base_path = os.path.dirname(os.path.abspath(__file__)) return os.path.join(base_path, relative_path) # 设置 QT_PLUGIN_PATH(必须在导入 PySide2 控件前完成) if hasattr(sys, '_MEIPASS'): plugins_path = resource_path('PySide2/plugins') if os.path.exists(plugins_path): os.environ['QT_PLUGIN_PATH'] = plugins_path print(f"🔧 已设置 QT 插件路径: {plugins_path}") else: print(f"❌ 插件路径不存在: {plugins_path}") # ========== 全局异常捕获(防止静默崩溃)========== def handle_exception(exc_type, exc_value, exc_traceback): error_msg = ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)) with open("error.log", "w", encoding="utf-8") as f: f.write(error_msg) QMessageBox.critical(None, "程序错误", f"发生未处理异常:\n{exc_value}\n详情见当前目录下的 error.log") # 启用全局异常钩子 import traceback sys.excepthook = handle_exception # ========== 数据库配置(db_config.py 内容内联)========== DB_CONFIG = { 'host': '192.168.110.204', 'port': 3306, 'user': 'Gapinyc', 'password': 'Gapinyc_2025', # 修改为实际密码 'database': 'gapinyc', 'charset': 'utf8mb4' } # ========== IP 映射表 ========== SORTERS = { '192.168.110.56': 1, '192.168.110.60': 2, '192.168.110.12': 3, '192.168.110.105': 4, '192.168.110.77': 5, '192.168.110.52': 6, '192.168.110.44': 7, '192.168.110.22': 8, '192.168.110.53': 9, '192.168.110.69': 0 # 服务端或测试机 } # ========== 获取本机 IP ========== def get_local_ip(): try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] if ip.startswith("192.168.") or ip.startswith("10.") or ip.startswith("172."): return ip else: return "127.0.0.1" except Exception as e: print(f"❌ 获取IP失败: {e}") return "127.0.0.1" # ========== 数据库管理类 ========== class DeviceManager: def __init__(self, linenumber): self.linenumber = str(linenumber) self.conn = None def connect(self): try: self.conn = pymysql.connect(**DB_CONFIG) return True except Exception as e: QMessageBox.critical(None, "数据库错误", f"无法连接数据库:\n{e}") return False def get_status(self): if not self.conn: return None, None try: with self.conn.cursor(pymysql.cursors.DictCursor) as cur: cur.execute( "SELECT status, nextwaybillid FROM ai_devicestatus WHERE linenumber = %s", (self.linenumber,) ) row = cur.fetchone() if row: return row['status'], row['nextwaybillid'] else: return None, None except Exception as e: QMessageBox.critical(None, "查询错误", f"读取设备状态失败:\n{e}") return None, None def update_offline_clear_bill(self): try: with self.conn.cursor() as cur: cur.execute(""" UPDATE ai_devicestatus SET status = 0, udtime = NOW(), nextwaybillid = NULL WHERE linenumber = %s """, (self.linenumber,)) self.conn.commit() return True except Exception as e: self.conn.rollback() QMessageBox.critical(None, "更新失败", f"更新数据库失败:\n{e}") return False def update_offline_only(self): try: with self.conn.cursor() as cur: cur.execute(""" UPDATE ai_devicestatus SET status = 0, udtime = NOW() WHERE linenumber = %s """, (self.linenumber,)) self.conn.commit() return True except Exception as e: self.conn.rollback() QMessageBox.critical(None, "更新失败", f"更新数据库失败:\n{e}") return False def update_online(self): try: with self.conn.cursor() as cur: cur.execute(""" UPDATE ai_devicestatus SET status = 1, udtime = NOW() WHERE linenumber = %s """, (self.linenumber,)) self.conn.commit() return True except Exception as e: self.conn.rollback() QMessageBox.critical(None, "上线失败", f"设备上线失败:\n{e}") return False def close(self): if self.conn and self.conn.open: self.conn.close() # ========== GUI 主窗口 ========== class SignInWindow(QWidget): def __init__(self): super().__init__() self.linenumber = None self.init_ui() self.check_device() def init_ui(self): self.setWindowTitle("分播机签到工具") self.setGeometry(300, 300, 400, 200) self.setFixedSize(400, 200) layout = QVBoxLayout() self.label = QLabel("正在检测设备...\n请勿关闭此窗口", self) self.label.setAlignment(Qt.AlignCenter) self.label.setWordWrap(True) self.btn_exit = QPushButton("退出") self.btn_exit.clicked.connect(self.close) layout.addWidget(self.label) layout.addWidget(self.btn_exit) self.setLayout(layout) def check_device(self): local_ip = get_local_ip() self.label.setText(f"本机IP: {local_ip}\n正在查映射...") if local_ip not in SORTERS: QMessageBox.critical(self, "设备错误", "该设备不在分播机IP映射表中,请联系管理员!") self.label.setText("❌ 设备不在映射表中\n请联系管理员。") return self.linenumber = SORTERS[local_ip] self.label.setText(f"识别成功!\n分播线: {self.linenumber}号线\n连接数据库...") dm = DeviceManager(self.linenumber) if not dm.connect(): self.label.setText("❌ 数据库连接失败") return status, next_waybill_id = dm.get_status() if status is None: QMessageBox.critical(self, "数据错误", f"未找到 lineNumber={self.linenumber} 的记录!") self.label.setText("❌ 数据库无此设备记录") dm.close() return # 状态判断逻辑 if status == 1 and next_waybill_id is None: reply = QMessageBox.question( self, "确认操作", "当前设备在线。\n如果需要设备下线,不再自动安排波次,请点击【确定】。\n否则点击【取消】。", QMessageBox.Yes | QMessageBox.No, QMessageBox.No ) if reply == QMessageBox.Yes: if dm.update_offline_only(): QMessageBox.information(self, "成功", "设备已下线,不再自动安排波次。\n祝您工作愉快,下班顺利,辛苦啦!!!") self.label.setText("设备已下线。\n签退完成。") else: self.label.setText("设备保持在线。\n无需操作。") elif status == 1 and next_waybill_id is not None: msg = f""" 当前设备在线,已经安排下一波次作业: 波次号为:{next_waybill_id} 请联系上级领导确认,以免影响您的绩效成绩! 请慎重选择!!! 如需不再进行下一波次作业, 请提前一个波次操作设备下线!!! 请问您确认不再进行下一波次作业吗? """.strip() reply = QMessageBox.question(self, "警告", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: if dm.update_offline_clear_bill(): QMessageBox.information( self, "成功", "设备已经下线,不再自动安排波次!\n" "祝您工作愉快,下班顺利,辛苦啦!!!" ) self.label.setText("设备已下线,波次已清空。") else: self.label.setText("设备保持在线,保留波次。") elif status == 0 and next_waybill_id is None: if dm.update_online(): QMessageBox.information( self, "签到成功", "恭喜您,签到成功!\n新的一天开始了,加油哦!!!\n稍后系统会自动给您安排波次,请耐心等待!!!" ) self.label.setText("✅ 签到成功!\n等待系统分配波次...") else: self.label.setText("❌ 上线失败,请联系管理员") elif status == 0 and next_waybill_id is not None: QMessageBox.critical( self, "系统错误", "系统逻辑错误:设备已下线但存在待处理波次!\n请立即联系上级领导核查!!!" ) self.label.setText("⚠️ 系统异常:请联系IT支持") dm.close() # ========== 启动入口 ========== if __name__ == '__main__': app = QApplication(sys.argv) window = SignInWindow() window.show() sys.exit(app.exec_()) 直接修改吧,提供修改后的完整代码
11-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值