Java – gniazda strumieniowe
//
Serwer usługi ECHO (protokol TCP)
//
import java.io.*;
import java.net.*;
class ObslugaKlienta extends Thread {
private Socket gniazdo;
private InputStreamReader wejscie;
private OutputStreamWriter wyjscie;
// -----------------------------------
public ObslugaKlienta(Socket polaczenie) throws IOException {
gniazdo = polaczenie;
wejscie = new InputStreamReader(gniazdo.getInputStream()); wyjscie = new OutputStreamWriter(gniazdo.getOutputStream()); start();
}
// ------------------------------------
public void run(){
int n;
long ident = getId();
char[] dane = new char[1000];
System.out.println(" - Watek obslugi [" + ident + "]"); try {
while (true) {
n = wejscie.read(dane,0,1000);
if (n != 0) {
String komunikat = new String(dane, 0, n); System.out.println("[" + ident + "] Serwer odebral od klienta "
+ gniazdo.getRemoteSocketAddress() + " komunikat - " + komunikat); wyjscie.write(dane,0,n);
wyjscie.flush();
}
else throw new IOException();
} //end while
} catch (Exception e) {
} finally {
try {
System.out.println("[" + ident + "] Rozlaczenie klienta - "
+ gniazdo.getRemoteSocketAddress());
gniazdo.close();
} catch(IOException e) {}
}
}
}
Opracował: Zbigniew Suski
1
Java – gniazda strumieniowe
public class EchoTCP_serwer {
public static final int PORT = 7000;
public static void main (String[] args) throws IOException {
ServerSocket nasluch = new ServerSocket(PORT); System.out.println("Czekam na zgloszenia klientow"); try {
while (true) {
Socket polaczenie = nasluch.accept();
System.out.printf("Zgloszenie klienta
- " +
polaczenie.getRemoteSocketAddress());
try {
new ObslugaKlienta(polaczenie);
} catch(IOException e) {
polaczenie.close();
}
}
// while
} finally {
// Opracowac zakonczenie pracy serwera
}
}
}
Opracował: Zbigniew Suski
2
Java – gniazda strumieniowe
//
Klient uslugi ECHO (protokol TCP)
//
import java.net.*;
import java.io.*;
public class EchoTCP_klient {
public static void main (String[] args) throws IOException {
InetAddress adresSerwera =
InetAddress.getByName(args.length !=1 ? "localhost" : args[0]); Socket gniazdo = new Socket(adresSerwera, EchoTCP_serwer.PORT); System.out.println("Podlaczenie do serwera: " +
gniazdo.getRemoteSocketAddress() +
" z portu " + gniazdo.getLocalPort()); try {
BufferedReader klawiatura = new BufferedReader(
new InputStreamReader(System.in));
InputStreamReader wejscie =
new InputStreamReader(gniazdo.getInputStream()); OutputStreamWriter wyjscie =
new OutputStreamWriter(gniazdo.getOutputStream()); String bufor_wy;
char [] dane = new char[1000];
int n;
while ((bufor_wy = klawiatura.readLine()).length() != 0) {
wyjscie.write(bufor_wy,0,bufor_wy.length());
// wysylanie bez NL
wyjscie.flush();
n = wejscie.read(dane,0,1000);
String bufor_we = new String(dane, 0 ,n); System.out.println("Klient odebral od serwera: " + bufor_we);
}
System.out.println("Koniec");
} finally {
gniazdo.close();
}
}
}
Opracował: Zbigniew Suski
3