Auf der Client-Seite bildet ein Telnet-Client das Gegenstück einer Verbindung zu dem Beispiel-Server. Der Telnet-Client lässt sich auf diese Art einsetzen, weil das Telnet-Protokoll lediglich Tastatureingaben vom Client zum Server bzw. Textausgaben vom Server zum Client überträgt.
public void startListening(int port, int backlog) throws IOException {
// Start a passive socket, step (1a).
ServerSocket passiveSocket = new ServerSocket(port, backlog);
// Now the passive socket is listening.
System.out.println("Server started on port " + port + ".");
boolean listen = true;
while(listen) {
// Blocking wait for a connection.
// If a client connects, a connection socket is returned
// by the passive socket.
Socket connectionSocket=passiveSocket.accept(); // step (1b+3)
handleConnection(connectionSocket); // step (4)
// Eventually, set boolean variable terminate.
...
}
}
private void handleConnection(Socket connectionSocket) throws IOException {
// Send a string to the client, step (4).
OutputStream os = connectionSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println("Tell me your name, please.");
pw.flush(); // "Flushing" empties the send buffer.
// Receive a string from the client, step (4).
InputStream is = connectionSocket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String name = br.readLine();
if (name != null) {
pw.println("Welcome " + name + "!");
pw.flush();
}
// Close the connections.
br.close();
pw.close();
}
package networkprotocol;
import java.net.*;
import java.io.*;
public class Server {
public void startListening(int port, int backlog) ...
private void handleConnection(Socket connectionSocket) ...
public static void main(String[] args) {
Server s = new Server();
int port = 2005;
int backlog = 100;
try {
s.startListening(port, backlog);
} catch (IOException ioe) {
System.out.println("There was an exception, the message is: " + ioe.getMessage());
}
}
}
[stein@webis stein]$
[stein@webis stein]$ telnet localhost 2005
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is ’ˆ]’.
Tell me your name, please.
Benno
Welcome Benno!
Connection closed by foreign host.
[stein@webis stein]$
status | not read | reprioritisations | ||
---|---|---|---|---|
last reprioritisation on | suggested re-reading day | |||
started reading on | finished reading on |