PDA

View Full Version : socket & thread



prashant
1st December 2009, 10:06
Related to : PyQt 4.6.1
This is regarding a simple socket reading in my application.
I am using QAbstractSocket.UdpSocket for the purpose.
Once the socket is connected to given host and port, it should constantly watch for data.

Question 1:
Do I have to use a thread to watch socket for data being available or signal "readyRead" will
do this job?

Question 2:
Code for sending data on socket:


socket = QtNetwork.QAbstractSocket(QtNetwork.QAbstractSocke t.UdpSocket, self)
socket.connectToHost(host, port)
socket.writeData("This is the test string.")
socket.disconnectFromHost()
socket.close()

The line:


socket.writeData("This is the test string.")

is crashing the application. why?

Question 3:
What's the proper way to close a socket?
I am using:


self.socket.disconnectFromHost()
self.socket.waitForDisconnected()
self.socket.close()

When I am closing the socket using above code, no error or warning is produced, but when I close the dialog box where I am implementing my tests, message is printed to stdout:


QWaitCondition: Destroyed while threads are still waiting


Please be patient, I have a limited knowledge on threads and sockets.

wysota
1st December 2009, 11:59
The socket will never be connected to a given host and port because UDP is a connectionless protocol. connectToHost() only states a default destination for write operations. Furthermore even if it was otherwise, connectToHost() and disconnectFromHost() are asynchronous operations - the methods return before the functionality it represents is executed thus writeData() will execute before connectToHost() even starts doing its job (at least in case of connection oriented protocols like TCP).

As for the first question - you don't need threads.

prashant
2nd December 2009, 10:09
Here are the two version of my Receiver & Sender scripts:
Receiver


# Start Communication.
if status:
# Create socket
self.socket = QtNetwork.QUdpSocket(self)
self.socket.setReadBufferSize(buffer)
self.socket.bind(QHostAddress.LocalHost, port, QtNetwork.QUdpSocket.ShareAddress)
self.socket.readyRead.connect(self.dataArrived)
msg=("Socket opened at host=%s, port=%d." % (host, port))
# Stop Communication.
else:
# Close socket
self.socket.disconnectFromHost()
self.socket.waitForDisconnected()
self.socket.close()
msg=("Socket closed at host=%s, port=%d." % (host, port))

Sender:


import socket

# Set the socket parameters
host = "localhost"
port = 6268
addr = (host, port)

service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

data = "This is a test string."
try:
service.connect(addr)
service.send(data)
except Exception, (value, message):
if service:
service.close()
print message
service.close()

The problem is in Receiver script