server.m
import java.net.*;
import java.io.*;
%% Create Socket
port = 20;
%input('Enter port number: ');
Server = ServerSocket (port);
disp('Waiting for a connection...')
connected = Server.accept;
iStream = connected.getInputStream;
oStream = connected.getOutputStream;
% Greets the client
oStream.sendS('Welcome client!')
% Waiting for messages from client
while ~(iStream.available)
end
readS(iStream);
%% Communication
msg = '';
while isempty(strfind(msg,'!q'))
% Waits for messages from client
while ~(iStream.available)
end
msg = readS(iStream);
if isempty(strfind(msg,'!q'))
% Sends message to client
disp 'Server''s turn!'
%cmd = input('Toclient>> ', 's');
cmd = 'hey im feeling okey!'
oStream.sendS(cmd);
else
oStream.sendS('!q');
end
end
pause(1)
connected.close;
disp (['Connection ended: ' datestr(now)]);
client.m
import java.net.*;
import java.io.*;
%% Create Socket and Connect to server
% Note that I am connecting to localhost, but you may change that to the corresponding machine IP that is running the server.
port = 20;
%input('Enter port number: ');
disp('Connecting to server...')
clientSocket = Socket('localhost', port);
iStream = clientSocket.getInputStream;
oStream = clientSocket.getOutputStream;
% Greets the server on connection is accepted
oStream.sendS('Hi Server!')
% Waiting for messages from Server
while ~(iStream.available)
end
readS(iStream);
msg = '';
while isempty(strfind(msg,'!q'))
% Sends message to server
disp 'Client''s turn!'
cmd = input('ToServer>> ', 's');
oStream.sendS(cmd);
% Waits for replies from server
while ~(iStream.available)
end
msg = readS(iStream);
end
clientSocket.close
disp (['Connection ended: ' datestr(now)]);
readS.m
function b = readS(iStream)
disp 'Reply:'
% Number of messages
n = iStream.available;
% Buffer size = 500 characters
b = zeros(1,500);
for i = 1:n
b(i) = iStream.read();
end
if (b(1) ~= 0)
disp (char(b))
end
disp ('')
sendS.m
function sendS(oStream,str)
oStream.write(int8([str 10]))