Sunday, March 3, 2013

communication between 3 PCs using UDP on Matlab

Years ago, I tried communication between PCs  using VC++ based on widows socket. It was not very difficult. But I never thought Matlab could also implement this. Today, I tried, it works:

For Server:
clear;
clc;
close all;

u=udp('172.21.168.xxx', 4013,'LocalPort', 14012);
fopen(u)
u1=udp('172.21.170.yyy', 4013,'LocalPort', 14013);
fopen(u1)
fwrite(u1, 1);
fwrite(u, 1);
fclose(u)
fclose(u1)

Above, '172.21.168.xxx' is the client1 ip, and 4013 is the client1 port no, while 14012 is the server port number;
'172.21.170.yyy' is the client2 ip, and 4013(any one if it is open to user) is  the client2 port no, while 14013 is the server port number;


For Client1:
u = udp('172.21.170.zzz',14012,'LocalPort',4012);
u.Timeout=1000;
fopen(u)
A = fread(u, 10);
fclose(u) 

Above, '172.21.170.zzz' is the server ip, port number is corresponded to the server port. u.Timeout=1000  means it will wait at most 1000s if it dose not receive any thing. however, as long as it recieve thedata from the server, it will jump to the next command directly.
fclose(u)  never forget to colse it when finished.

For Client2:
u = udp('172.21.170.zzz',14013,'LocalPort',4013);
u.Timeout=1000;
fopen(u)
A = fread(u, 10);
fclose(u) 

3 comments:

  1. hi, I also work on this recently, talk to u later, ha~~

    ReplyDelete
  2. Hi, How should I execute that? first the code of server, then the client 1 and then the client 2 because the server's message doesn't come to the client 1 because yet there is not any conection. or I shuld execute the part of code of clients and server where I make the conection and then I send the message?
    Thank you.

    ReplyDelete