Python and MATLAB in the socket
13 views (last 30 days)
Show older comments
I need a way to communicate dynamically between Python and MATLAB, so I am currently trying to connect python and MATLAB through socketing. Although I can get Python to work with socket and MATLAB with the tcpip functionality, they seem unable to sense each other despite being connected to the same tcp port. I can write to the port in each environment and read the data, but one environment cannot seem to detect the data sent it by the other.
MATLAB code
path=input('Please enter the location of the GDSII file: ','s');
echotcpip('on',1722)
sock = tcpip('localhost',1722);
fopen(sock);
fwrite(sock,path);
pause(1);
system('C:/Python27/Scripts/SpectrumAcquire/SetPoints.py')
Python Code
from Tkinter import *
from gdspy import *
from socket import *
#Use this port to read data from matlab
socky = socket(AF_INET,SOCK_STREAM)
host2='localhost'
port2 = 1722
addr2 = (host2,port2)
socky.connect(addr2)
print "socky connected"
print socky.recv(78) #print path
The recv function just hangs when running in either Python or MATLAB, so I am not sure what the problem is.
Thank you in advance for any help.
1 Comment
Zenas Savage
on 22 Jun 2015
Did you ever find a solution to your problem? I think I'm dealing with something similar.
Answers (1)
Robert Snoeberger
on 28 Jun 2015
Example
Connect to Python echo server from MATLAB. The echo server code is given as an example in the Python socket documentation. See here .
Python echo server script - echoserver.py
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Python code was obtained from the Python socket documentation.
MATLAB client code
>> % start the echo server
>> !python echoserver.py &
>>
>> % connect to the server
>> t = tcpip('localhost', 50007);
>> fopen(t);
>>
>> % write a message
>> fwrite(t, 'This is a test message.');
>>
>> % read the echo
>> bytes = fread(t, [1, t.BytesAvailable]);
>> char(bytes)
ans =
This is a test message.
>>
>> % close the connection
>> fclose(t);
1 Comment
Kai Chuen Tan
on 3 Oct 2019
Edited: Kai Chuen Tan
on 3 Oct 2019
Can I write a message in an array of integers in MATLAB like "fwrite(t, [1 2 3])"?
If yes, how can I extract the second element of the array (i.e., 2) from the python? Do I code something like:
"data = conn.recv(1024)"
"secData = data[2]"
?
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!