【问题标题】:Chat programming with PyQt and Socket [Standard Library]使用 PyQt 和 Socket 进行聊天编程 [标准库]
【发布时间】:2012-01-14 16:20:26
【问题描述】:

我写了一个程序,在客户端部分经常出现错误,我认为错误来自client.py中的socket函数。我该怎么办?

server.py:

# This is my server code , this code has no problems
import asyncore
import socket

clients = {}

class MainServerSocket(asyncore.dispatcher):
    def __init__(self, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(('',port))
        self.listen(5)
    def handle_accept(self):
        newSocket, address = self.accept( )
        clients[address] = newSocket
        print "Connected from", address
        SecondaryServerSocket(newSocket)

class SecondaryServerSocket(asyncore.dispatcher_with_send):
    def handle_read(self):
        receivedData = self.recv(8192)
        if receivedData:
            every = clients.values()
            for one in every:
                one.send(receivedData+'\n')
        else: self.close( )
    def handle_close(self):
        print "Disconnected from", self.getpeername( )
        one = self.getpeername( )
        del clients[one]

MainServerSocket(21567)
asyncore.loop( )

client.py:

from PyQt4 import QtGui , QtCore
from socket import *
import thread
import sys

HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.socket()

        roomLabel = QtGui.QLabel('room')

        self.browser = QtGui.QTextBrowser()
        self.browser.backwardAvailable

        self.textEdit = QtGui.QTextEdit()
        self.textEdit.setMaximumSize(QtCore.QSize(400,60))
        #4 edit line
        self.connect(self.browser, QtCore.SIGNAL("returnPressed()"),self.callback)

        SendButton = QtGui.QPushButton('Send')
        SendButton.setMaximumSize(QtCore.QSize(400,60))
        SendButton.clicked.connect(self.callback)




        layoutINlayout = QtGui.QHBoxLayout()
        layoutINlayout.addWidget(self.textEdit)
        layoutINlayout.addWidget(SendButton)


        widget = QtGui.QWidget()
        self.setCentralWidget(widget)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.browser)

        mainwindow = QtGui.QVBoxLayout()
        mainwindow.addLayout (self.layout )
        mainwindow.addLayout (layoutINlayout )

        widget.setLayout(mainwindow)
        self.setWindowFlags(QtCore.Qt.WindowTitleHint )

    def callback(self, event):

        message = self.textEdit.toPlainText()
        tcpCliSock.send(message)



    def add(self, data):
        self.browser.setText(data)


    #i think the error comes from socket func:
    def socket(self):

        def loop0():
            while 1:
                print '1'
                data = tcpCliSock.recv(BUFSIZE)
                if data: self.add(data)

        thread.start_new_thread(loop0, ())


if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    app.setStyle('chat')


    window = MainWindow()
    window.setWindowTitle("pro IJ cracker v2")
    window.setWindowIcon(QtGui.QIcon("img/go.png"))
    window.show()
    sys.exit(app.exec_())

【问题讨论】:

  • 发生什么错误?您能解释一下您预计会发生什么以及您遇到的问题是什么吗?
  • yes:) 错误是: 启动的线程中出现未处理的异常
  • 当客户端发送消息时,您的服务器代码给了我AttributeError: 'SecondaryServerSocket' object has no attribute 'getpeername'

标签: python sockets pyqt chat


【解决方案1】:

我的建议是

1) 使用 QThread

2) 不要直接从另一个线程修改主线程中的小部件。相反,每次有数据时,您的 QThread 都会发出一个信号。

还有一些关于为什么您当前的线程设置崩溃的快速信息,请尝试包装并打印异常:

    def loop0():
        while 1:
            print '1'
            try:
                data = tcpCliSock.recv(BUFSIZE)
                if data: self.add(data)
            except Exception, e:
                print "ERROR:", e
                raise

【讨论】:

  • @irajjelodari 你能发布你的最终结果吗?有点我也在同一个问题上
猜你喜欢
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
  • 2014-12-21
相关资源
最近更新 更多