85 lines
2.2 KiB
Java
85 lines
2.2 KiB
Java
import java.net.*;
|
|
import java.io.*;
|
|
|
|
public class Client
|
|
{
|
|
public static void main(String args[])
|
|
{
|
|
//pobranie i sprawdzenie otrzymanych argumentów
|
|
if (args.length < 2){
|
|
System.out.println("Wywołanie programu: Client host port");
|
|
System.exit(-1);
|
|
}
|
|
String host = args[0];
|
|
int port = 0;
|
|
try{
|
|
port = Integer.valueOf(args[1]);
|
|
}
|
|
catch(NumberFormatException e){
|
|
System.out.println("Nieprawidłowy argument: port");
|
|
System.exit(-1);
|
|
}
|
|
//Inicjalizacja gniazda klienckiego
|
|
Socket clientSocket = null;
|
|
try{
|
|
clientSocket = new Socket(host, port);
|
|
}
|
|
catch(UnknownHostException e){
|
|
System.out.println("Nieznany host.");
|
|
System.exit(-1);
|
|
}
|
|
catch(ConnectException e){
|
|
System.out.println("Połączenie odrzucone.");
|
|
System.exit(-1);
|
|
}
|
|
catch(IOException e){
|
|
System.out.println("Błąd wejścia-wyjścia: " + e);
|
|
System.exit(-1);
|
|
}
|
|
System.out.println("Połączono z " + clientSocket);
|
|
|
|
//Deklaracje zmiennych strumieniowych
|
|
String line = null;
|
|
BufferedReader brSockInp = null;
|
|
BufferedReader brLocalInp = null;
|
|
DataOutputStream out = null;
|
|
|
|
//Utworzenie strumieni
|
|
try{
|
|
out = new DataOutputStream(clientSocket.getOutputStream());
|
|
brSockInp = new BufferedReader(
|
|
new InputStreamReader(
|
|
clientSocket.getInputStream()));
|
|
brLocalInp = new BufferedReader(
|
|
new InputStreamReader(System.in));
|
|
}
|
|
catch(IOException e){
|
|
System.out.println("Błąd przy tworzeniu strumieni: " + e);
|
|
System.exit(-1);
|
|
}
|
|
//Pętla główna klienta
|
|
while(true){
|
|
try{
|
|
line = brLocalInp.readLine();
|
|
if(line != null){
|
|
System.out.println("Wysyłam: " + line);
|
|
out.writeBytes(line + '\n');
|
|
out.flush();
|
|
}
|
|
if(line == null || "quit".equals(line)){
|
|
System.out.println("Kończenie pracy...");
|
|
clientSocket.close();
|
|
System.exit(0);
|
|
}
|
|
brSockInp.readLine();
|
|
System.out.println("Otrzymano: " + line);
|
|
}
|
|
catch(IOException e){
|
|
System.out.println("Błąd wejścia-wyjścia: " + e);
|
|
System.exit(-1);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|