Matlab和C ++之间的TCP / IP通信

时间:2013-04-21 10:16:14

标签: c++ matlab tcp-ip

我在Matlab和C ++之间的TCP / IP通信方面存在问题。我使用MWinsock在C ++中创建服务器,可以从客户端发送和接收数据。在Matlab(充当客户端)中,我创建TCP / IP对象,连接到服务器,并使用fprintf向服务器发送文本[例如,我将文本“A005”发送到服务器,fprintf(t, 'A005') ]。但是,在C ++上运行的服务器上只接收一些空文本''或仅接收'05'或'A0',有时是'A005'。所以,任何人都可以帮助解决这个问题,非常感谢!


感谢您的回答, 代码实际上很简单

*在Matlab中,使用TCP / IP对象:

t = tcpip('IPaddress', 1200); %IPaddress get from server after running 'winServer.exe' file.
fopen(t);  
fprintf(t, 'A005')

*在服务器上,我使用LiyangYu开发的服务器文件(您可以从here下载.exe文件)。

我尝试了如上所述的问题,所以你能给出任何解决方案吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

您是否真的阅读了linked to项目的代码和说明?您不能只选择一些随机代码并期望它能够正常工作!

这是一个基本的TCP聊天服务器的例子(如果你问我,编程很差)。它适用于根据特定约定格式化的消息:

  • 消息长度(6个字符右对齐填充空格):sprintf('%6d',len)
  • 后跟实际消息字符串

话虽如此,这里有一个简单的MATLAB客户端与C ++聊天服务器进行交互:

%# helper functions to send/receive messages according to the protocol
send = @(t,msg) fwrite(t, [sprintf('%6d',length(msg)) msg], 'uint8');
recv = @(t) char(fread(t, str2double(char(fread(t,6,'uint8')')), 'uint8')');

%# connect to server
t = tcpip('127.0.0.1',1200);
fopen(t);

%# send a message
send(t,'hello there')

%# receive response and display it
m = recv(t);
fprintf('[SERVER]: %s\n', m);

%# send BYE message to disconnect from chat
send(t,'bye')

%# close socket and clear it
fclose(t);
delete(t); clear t

当然,服务器winserver.exe必须首先在一个单独的控制台中运行(不要忘记在那里键入您的消息以响应客户端)

相关问题