为此应用添加Qt套接字代码,以启用两台PC之间的聊天

时间:2016-12-22 07:25:05

标签: python qt5 pyqt5

任何人都可以帮我这个代码吗?如何在此程序中添加P2P聊天代码? 我希望能够通过LAN在两台PC之间聊天

enter image description here

import sys, os
import socket 

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,
  QLineEdit, QFileDialog, QInputDialog, QFileDialog,QMessageBox, QMenuBar)

from PyQt5.QtGui import QIcon
from PyQt5.Qt import QPushButton, QTextEdit, QMessageBox

class myApp (QMainWindow):
    def __init__(self):
        super().__init__()

self.initUI()

def initUI(self):

    self.main_text      =       QtWidgets.QTextEdit(self)
    self.send_box       =       QtWidgets.QLineEdit(self)
    self.connect_btn    =       QtWidgets.QPushButton('Connect', self)
    self.browse_btn     =       QtWidgets.QPushButton('Browse',self)
    ip_add_box          =       QtWidgets.QLineEdit(self)
    port_box            =       QtWidgets.QLineEdit(self)




    self.main_text.setGeometry(25, 30, 360, 350)
    self.send_box.setGeometry(25, 400, 360, 60)
    ip_add_box.setGeometry(25, 530, 150, 30)
    port_box.setGeometry(180, 530, 90,30)
    self.connect_btn.setGeometry(25, 500, 70, 25)
    self.browse_btn.setGeometry(100,500,70,25)

    self.setGeometry(200,100,400,580)
    self.setWindowTitle('My Application')
    self.setWindowIcon(QIcon('icon.png'))

    # CODE BLOCK FOR EVENTS
    self.send_box.returnPressed.connect(self.sendData)      # EnterPressed Event for SendBox LineEdit
    self.connect_btn.clicked.connect(self.connectNet)       # Socket Connect event for the connect Button        
    self.browse_btn.clicked.connect(self.BrowseFile)        # Browse file connect event for Browse Button


    self.show()

def sendData(self):
    self.main_text.append( self.send_box.text() )
    self.send_box.clear()
def connectNet(self):
    host = 'localhost'
    port = 12345
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (host, port)
    print ("Connecting to %s port %s" % server_address)
    sock.connect(server_address)

    try: 
        message = "Test message. This will be echoed"
        print ("Sending %s" % message)
        sock.sendall(message)
        # Look for the response
        amount_received = 0
        amount_expected = len(message)
        while amount_received < amount_expected:
            data = sock.recv(16)
            amount_received += len(data)
            print ("Received: %s" % data)
    finally:
        print ("Closing connection to the server")
        sock.close()

def BrowseFile (self):
    filePath    =   QtWidgets.QFileDialog.getOpenFileName(self)






if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = myApp()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

最后解决了这个问题。客户端就在这里

from PyQt5 import QtCore, QtWidgets, QtWidgets, QtNetwork

class Client(QtWidgets.QDialog):

def __init__(self, parent=None):
    super(Client, self).__init__(parent)

    self.main_text = QtWidgets.QTextEdit(self)
    self.main_text.setReadOnly(True)
    self.send_box = QtWidgets.QLineEdit(self)
    self.send_button = QtWidgets.QPushButton("Send", self)
    self.browse_btn = QtWidgets.QPushButton("Browse", self)
    # EVENT FOR SEND BUTTON
    self.send_button.clicked.connect(self.sendData)

    self.server_ip = QtWidgets.QLineEdit(self)
    self.server_ip.setPlaceholderText("IP address")
    self.port_address = QtWidgets.QLineEdit(self)
    self.port_address.setPlaceholderText("port")

    self.userName = QtWidgets.QLineEdit(self)
    self.userName.setPlaceholderText("username")

    self.connectButton = QtWidgets.QPushButton("Connect",self)
    #Connect Button EVENT
    self.connectButton.clicked.connect(self.connection)
    self.connectButton.setDefault(True)

    self.setGeometry(400,50,500,600)
    self.main_text.setGeometry(25,50,450,400)
    self.send_box.setGeometry(25,470,450,40)
    self.send_button.setGeometry(385,520,90,30)
    self.browse_btn.setGeometry(25,520,100,30)
    self.server_ip.setGeometry(150,10,130,25)
    self.port_address.setGeometry(300,10,70,25)
    self.connectButton.setGeometry(385,10,90,25)
    self.userName.setGeometry(25,10,120,25)


    #NetworkInput
    self.socket = QtNetwork.QTcpSocket(self)
    self.socket.readyRead.connect(self.readData)
    self.socket.error.connect(self.displayError)

def closeEvent(self, event):
    self.socket.disconnectFromHost()

def connection(self):
    self.socket.connectToHost(self.server_ip.text(), int(self.port_address.text()))
    if self.socket.waitForConnected(1000):
        self.user = self.userName.text()
        self.send("login %s" % self.user)
        self.connectButton.setEnabled(False)
        self.send_button.setDefault(True)
        self.send_box.setFocus()
        #self.setWindowTitle("<%s>" % self.user)
def readData(self):
    message = self.socket.readLine().data().decode("utf-8")
    self.main_text.append(message)

def send(self, message):
    self.socket.write(message.encode("utf-8"))

def sendData(self):
    message = "say %s" % (self.send_box.text())
    self.send(message)
    self.send_box.clear()
    self.send_box.setFocus()

def displayError(self):
    QtWidgets.QMessageBox.information(self, "Connection", "Connection error")


if __name__ == "__main__":
   import sys
   app = QtWidgets.QApplication(sys.argv)
   client = Client()
   sys.exit(client.exec_())