Python and MATLAB in the socket

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

Zenas Savage
Zenas Savage 2015년 6월 22일
Did you ever find a solution to your problem? I think I'm dealing with something similar.

댓글을 달려면 로그인하십시오.

답변 (1개)

Robert Snoeberger
Robert Snoeberger 2015년 6월 28일

1 개 추천

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

Kai Chuen Tan
Kai Chuen Tan 2019년 10월 3일
편집: Kai Chuen Tan 2019년 10월 3일
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]"
?

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Call MATLAB from Python에 대해 자세히 알아보기

질문:

2012년 10월 6일

편집:

2019년 10월 3일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by