Borrar filtros
Borrar filtros

Multi client TCP/IP communication

15 visualizaciones (últimos 30 días)
chizom wornu
chizom wornu el 13 de Feb. de 2024
Editada: chizom wornu el 14 de Feb. de 2024
Hello I have been working on this TCP communication. I have been able to implement, the server and client communication. However, I have multiple clients (4). How do I make my server listen for new connection after receiving the first connection. Below are my codes. When I run my code, the first client connects, however the second clients does not connect.
SERVER CODE
clear;
clc;
% Create a TCP/IP server
serverAddress = '0.0.0.0';
serverPort = 5000;
serverSocket = tcpip(serverAddress, serverPort, 'NetworkRole', 'server');
% Open server socket
fopen(serverSocket);
disp('Server: Listening for client connections...');
try
% Accept four client connections
for i = 1:4
disp(['Server: Waiting for client ', num2str(i), ' to connect...']);
clientSocket = acceptConnection(serverSocket);
disp(['Server: Client ', num2str(i), ' connected.']);
% Receive data from client
dataBytes = fread(clientSocket, 192, 'uint8');
disp(['Server: Received data from client ', num2str(i)]);
% Convert byte data back to a numeric array
receivedData = zeros(24, 1); % Initialize the array to hold the received data
for j = 1:24
% Extract the 8 bytes corresponding to one double-precision number
byteBlock = dataBytes((j-1)*8 + (1:8));
% Convert the byte block to a double-precision number
receivedData(j) = typecast(uint8(byteBlock), 'double');
end
% Process the received data as needed
disp(['Server: Received data array: ', mat2str(receivedData)])
response = 4*4;
dataBytes_send = typecast(response, 'uint8')
% Send response back to client
fwrite(clientSocket, dataBytes_send);
disp(['Server: Response sent to client ', num2str(i)]);
% Close connection with the client
fclose(clientSocket);
disp(['Server: Connection with client ', num2str(i), ' closed.']);
end
% Close server
fclose(serverSocket);
disp('Server: Disconnected.');
catch exception
% Close server and display error message
fclose(serverSocket);
disp(['Server: Error occurred - ', exception.message]);
end
function clientSocket = acceptConnection(serverSocket)
timeout = 20; % seconds
tic;
while serverSocket.BytesAvailable == 0
if toc > timeout
error('Server: Connection timeout.');
end
end
clientSocket = serverSocket;
end
Client 1
% Create a TCP/IP client for sending solar power data
clientSolar = tcpclient('127.0.0.1', 5000);
try
% Connect to the server
fopen(clientSolar);
disp('Solar Client: Connected to server.');
% Convert data to bytes
solar_power_bytes = typecast(solar_power(:), 'uint8');
% Send solar power data to the server
fwrite(clientSolar, solar_power_bytes);
disp('Solar Client: Solar power data sent to server.');
% Receive response from server
dataBytes_R = read(clientSolar, 8, 'uint8');
receivedData = typecast(dataBytes_R, 'double');
% Display received data
disp(['Received response from server for solar: ', num2str(receivedData)])
% Close connection
fclose(clientSolar);
disp('Solar Client: Disconnected from server.');
catch exception
% Close connection and display error message
fclose(clientSolar);
disp(['Solar Client: Error occurred - ', exception.message]);
end
Client 2
% Create a TCP/IP client for sending wind power data
clientWind = tcpclient('127.0.0.1', 5000);
try
% Connect to the server
fopen(clientWind);
disp('Wind Client: Connected to server.');
% Convert data to bytes
Wind_power_bytes = typecast(solar_power(:), 'uint8');
% Send solar power data to the server
fwrite(clientSolar, Wind_power_bytes);
disp('Wind Client: Wind power data sent to server.');
% Receive response from server
dataBytes_R = read(clientWInd, 8, 'uint8');
receivedData = typecast(dataBytes_R, 'double');
% Display received data
disp(['Received response from server for solar: ', num2str(receivedData)])
% Close connection
fclose(clientWind);
disp('Wind Client: Disconnected from server.');
catch exception
% Close connection and display error message
fclose(clientWind);
disp(['Wind Client: Error occurred - ', exception.message]);
end

Respuesta aceptada

Hassaan
Hassaan el 13 de Feb. de 2024
Editada: Hassaan el 13 de Feb. de 2024
@chizom wornu Some of the recommendations. See also the reference link.
MATLAB's Limitations: Unfortunately, MATLAB's built-in tcpip object does not natively support acting as a server that can accept multiple connections by itself.
Alternative MATLAB Approach: Consider using MATLAB's ability to interface with Java for more advanced networking capabilities. MATLAB can directly use Java classes, allowing you to implement a multi-client TCP server using Java's networking libraries. This requires knowledge of Java but can be more flexible and powerful than relying on MATLAB's built-in functions alone.
MATLAB External Interfaces: If your application must remain within MATLAB for other reasons (e.g., specialized mathematical or signal processing workflows), you can develop the TCP server in another language that is better suited for network programming and then interface with MATLAB using a mechanism like a MATLAB Engine API for Python, Java, or calling compiled C/C++ libraries from MATLAB.
Reference:
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.
  1 comentario
chizom wornu
chizom wornu el 14 de Feb. de 2024
Editada: chizom wornu el 14 de Feb. de 2024
I just sent all the data using one client. Am not good with Java

Iniciar sesión para comentar.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!

Translated by