Program mychat;
uses Sockets, crt;
Var
sc:char;
Buffer : string[255];
S : Longint;
Sin,Sout : Text;
SAddr : TInetSockAddr;
Com : Boolean;
Nome : String;
procedure perror (const S:string);
begin
writeln ('Errore --> ',S,SocketError);
readln;
halt(100);
end;
BEGIN
S:=Socket (AF_INET,SOCK_STREAM,0);
if SocketError<>0 then Perror ('Socket : '); //
SAddr.sin_family:=AF_INET;
SAddr.sin_port:=htons(50000); // porta 50000, puoi sceglierne un'altra
SAddr.sin_addr.s_addr:=hosttonet((127 shl 24)or 1); //indirizzo IP locale
writeln('Vuoi esser client o server (immetti c/s)');
repeat readln(sc); until (sc='c') or (sc='s');
if sc='s' then begin
nome := 'server';
if not Bind(S,SAddr,sizeof(saddr)) then PError ('Server : Bind : ');
if not Listen (S,1) then PError ('Server : Listen : ');
Writeln('Sono in attesa di un client ... ');
if not Accept (S,Saddr,Sin,Sout) then PError ('Server : Accept : ')
else writeln('Client connesso, aspetta il suo primo messaggio');
end else begin
nome := 'client';
if not Connect (S,SAddr,Sin,Sout) then PError('Client : Connect : ')
else writeln('Sei connesso al server, invia tu il primo messaggio');
end;
writeln('Inserisci una stringa vuota per terminare la comunicazione');
writeln;
com := true;
Reset(Sin);
if sc='c' then begin //Il client invia il primo messaggio
ReWrite(Sout);
buffer := '';
textcolor(14); readln(buffer); textcolor(7);
writeln(Sout,buffer);
if length(Buffer)=0 then begin
com:=false;
end;
end;
while com do begin // Comunicazione
Readln(Sin,Buffer);
writeln(' Messaggio dal ', nome );
if length(Buffer)=0 then begin
com:=false;
continue;
end;
textcolor(14); writeln(buffer); textcolor(7);
ReWrite(Sout);
buffer := '';
writeln(' Scrivi un messaggio per il ', nome);
textcolor(14);
readln(buffer);
textcolor(7);
writeln(Sout,buffer);
if length(Buffer)=0 then begin
com:=false;
continue;
end;
end;
writeln;
writeln('Comunicazione terminata');
readln;
END.