Error Socket connection

Hi Team,
We are trying to connect device which support TCP communication. We are trying to do communication over the web socket. I write below code sometimes its works correctly but some time its gets "[Errno 10061] Connection refused"

Code:


try:	
	import socket
	import sys
	address='10.192.9.70'
	port=8888
	
	s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	print s
	s.connect((address,port))	
	print  s	
	cmd1='LLFT?\r\n'
	s.sendall(cmd1.encode())
	buf=s.recv(256)

	CHTemp= repr(buf)

	CHTemp1= CHTemp.split("\\")
	CHTempScalled= (CHTemp1[0])
	LeftLoop1= (CHTempScalled[1:])
	if LeftLoop1=='' or LeftLoop1==None:
		LeftLoop1=0
	else:
		pass

	s.close
	print  LeftLoop1
except:
	exc_type, exc_obj,tb = sys.exc_info()
	errorMessage = "Error:"+ str(exc_obj)
	print(errorMessage)
	lineno = tb.tb_lineno
	s.close
	print(lineno)
	sys.exit()

Error:
Error:[Errno 10061] Connection refused

Please help us to resolve issue.

Normally connection refused if the port you're trying to go to doesn't accept the connection. Make sure whatever you're connecting to is set to accept your connection.

Also be careful using the python socket module, it has some pretty bad memory leaks. I think the recommendation on the forum is to use the Java based socket as that seems to run a bit better. Using from java.net import Socket but you'll need to read the java documentation on how to use it.

1 Like

Hello @Hayden_Watson,
Im not much aware of java-based socket programming. it will be helpful if share some resource or code example through which we can send command in socket programing.
I have one doubt it can be work i ignition (Scripting consol, gateway script)?

Please see Wiki - how to post code on this forum. There's a link (pencil icon) below your post to edit and fix it. Thanks.

As I said, you'll need to look into the java class docs. When I did it we had to convert our data into an array of bytes and send that down the socket, then read a response.

Using code like:

from java.net import Socket as javaSocket
import jarray
skt = javaSocket(ip_addr, port) #Java Socket declare
out_stream = skt.getOutputStream() # set socket send data stream

b_msg = jarray.array(to_convert_b_msg,'b') # Create Java array object for data transmission
		
out_stream.write(b_msg,0,len(b_msg)) # Write Data

This code won't work obviously but should be able to start to look up Java docs on how to implement for your case.

We did find that it massively reduced the memory leaking, so worth the time investment, but my java/Jython skills are pretty poor so maybe isn't super complciated to others.

This is the thread people helped me out on, though took some extra time to figure out how to get it working after

1 Like