Python and MATLAB in the socket

41 次查看(过去 30 天)
Brian
Brian 2012-10-6
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
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]"
?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by