applicazione client server

annuncio pubblicitario
Il seguente listato mostra come creare una semplice applicazione di console utilizzando le socket connections.
La comunicazione è di tipo uno a uno.
Dopo aver compilato client e server avviare prima il server, dopo aver avviato anche il client sarà possibile passare
messaggi al server che risponderà
restituendo il messaggio in caratteri maiuscoli.
Server e client terminano quando il client riceve la parola “exit”.
Ricordarsi di inserire l’indirizzo IP corretto (o "host = here.getHostName ()" nel caso in cui si lavori con una sola
postazione).
CLIENT
import
import
java.io.*;
java.net.*;
public
{
class tcpclient
public
{
static
void
main(String[] args) throws Exception
String
message="in";
String
modifiedmessage;
BufferedReader inkbd =
new BufferedReader(new InputStreamReader(System.in));
InetAddress here = InetAddress.getLocalHost ();
String host = here.getHostName ();
//String host = "xx.xx.xx.xx";
//Socket
Socket
csock = new Socket("www.abcd.it",6789);
csock = new Socket(host,6789);
DataOutputStream out =
new DataOutputStream(csock.getOutputStream());
BufferedReader innet =
new BufferedReader(new
InputStreamReader(csock.getInputStream()));
while (!(message.equalsIgnoreCase("exit")))
{
message = inkbd.readLine();
//
System.out.println("client:"+message);
out.writeBytes(message + "\n");
modifiedmessage = innet.readLine();
System.out.println("Server sent :- " + modifiedmessage);
}
csock.close();
}
}
SERVER
import
import
java.io.*;
java.net.*;
public
class tcpserver
{
public
{
static
void
main(String args[]) throws Exception
String
message="in";
String
messageout;
String
risposta;
ServerSocket ssock = new ServerSocket(6789);
Socket
connsock = ssock.accept();
BufferedReader inkbd =
new BufferedReader(new
InputStreamReader(System.in));
InputStreamReader instr =
new InputStreamReader(connsock.getInputStream());
DataOutputStream outstr =
new DataOutputStream(connsock.getOutputStream());
BufferedReader innet = new BufferedReader(instr);
while (!(message.equalsIgnoreCase("exit")))
{
message = innet.readLine();
//System.out.println("Client sent :" + message);
//System.out.println("\nRisposta: ");
//risposta = inkbd.readLine();
//messageout = message.toUpperCase() + ": Risposta =" +
risposta + "\n";
messageout = message.toUpperCase() + "\n";
outstr.writeBytes(messageout);
}
}
}
Scarica