Python and MATLAB in the socket

56 ビュー (過去 30 日間)
Brian
Brian 2012 年 10 月 6 日
編集済み: Kai Chuen Tan 2019 年 10 月 3 日
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 Center および File ExchangeCall Python from MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by