0% found this document useful (0 votes)
40 views

Java Networking - Socket A Simple Echo Server: Serversocket

This document describes a simple echo server and client written in Java using sockets for network communication. The server waits for client connections, reads input from each client, and writes it back. The client connects to the server, sends input, and prints the response. The document also discusses enhancements like a multi-threaded server to handle multiple clients simultaneously and a visitor counter server that tracks counts in a file.

Uploaded by

luc4smoreira
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Java Networking - Socket A Simple Echo Server: Serversocket

This document describes a simple echo server and client written in Java using sockets for network communication. The server waits for client connections, reads input from each client, and writes it back. The client connects to the server, sends input, and prints the response. The document also discusses enhancements like a multi-threaded server to handle multiple clients simultaneously and a visitor counter server that tracks counts in a file.

Uploaded by

luc4smoreira
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

A Simple Echo Server

Java Networking -- Socket


import java.io.*;
import java.net.*;
Server socket class: ServerSocket
public class EchoServer {
wait for requests from clients. public static void main(String[] args) {
after a request is received, a client socket is generated. try {
Client socket class: Socket ServerSocket s = new ServerSocket(8008);
while (true) {
an endpoint for communication between two apps/applets. Socket incoming = s.accept();
obtained by BufferedReader in
contacting a server = new BufferedReader(
generated by the server socket new InputStreamReader(
incoming.getInputStream()));
Communication is handled by input/output streams. PrintWriter out
Socket provides an input and an output stream. = new PrintWriter(
new OutputStreamWriter(
incoming.getOutputStream()));

A Simple Echo Server (cont'd)


out.println("Hello! ....");
out.println("Enter BYE to exit.");
Test the EchoServer with Telnet
out.flush();
while (true) {
String str = in.readLine(); Use telnet as a client.
if (str == null) {
break; // client closed connection venus% telnet saturn 8008
} else { Trying 140.192.34.63 ...
out.println("Echo: " + str); Connected to saturn.
out.flush(); Escape character is '^]'.
if (str.trim().equals("BYE")) Hello! This is the Java EchoServer.
break; Enter BYE to exit.
} Hi, this is from venus
} Echo: Hi, this is from venus
incoming.close(); BYE
} Echo: BYE
} catch (Exception e) {} Connection closed by foreign host.
}
}
A Simple Client (cont'd)
A Simple Client (class EchoClient continued.)

BufferedReader in
import java.io.*;
= new BufferedReader(
import java.net.*;
new InputStreamReader(
socket.getInputStream()));
public class EchoClient {
PrintWriter out
= new PrintWriter(
public static void main(String[] args) {
new OutputStreamWriter(
try {
socket.getOutputStream()));
String host;
// send data to the server
if (args.length > 0) {
for (int i = 1; i <= 10; i++) {
host = args[0];
System.out.println("Sending: line " + i);
} else {
out.println("line " + i);
host = "localhost";
out.flush();
}
}
Socket socket = new Socket(host, 8008);
out.println("BYE");
out.flush();

Multi-Threaded Echo Server


A Simple Client (cont'd) To handle multiple requests simultaneously.
In the main() method, spawn a thread for each
(class EchoClient continued.) request.
// receive data from the server public class MultiEchoServer {
while (true) {
String str = in.readLine(); public static void main(String[] args) {
if (str == null) { try {
break; ServerSocket s = new ServerSocket(8009);
} else { while (true) {
System.out.println(str); Socket incoming = s.accept();
} new ClientHandler(incoming).start();
} }
} catch (Exception e) {} } catch (Exception e) {}
} }
}
}
Client Handler Client Handler (cont'd)
public class ClientHandler extends Thread { out.println("Hello! ...");
out.println("Enter BYE to exit.");
protected Socket incoming; out.flush();
while (true) {
public ClientHandler(Socket incoming) { String str = in.readLine();
this.incoming = incoming; if (str == null) {
} break;
public void run() { } else {
try { out.println("Echo: " + str);
BufferedReader in out.flush();
= new BufferedReader( if (str.trim().equals("BYE"))
new InputStreamReader( break;
incoming.getInputStream())); }
PrintWriter out }
= new PrintWriter( incoming.close();
new OutputStreamWriter( } catch (Exception e) {}
incoming.getOutputStream())); }
}

Visitor Counter Visitor Counter Server


public class CounterServer {
A server and an applet.
The server keeps the visitor count in a file, and public static void main(String[] args) {
sends the count to clients when requested. System.out.println("CounterServer started.");
int i = 1;
No need for spawning thread, since only need to try {
transmit an integer. // read count from the file
InputStream fin =
Read and write files. new FileInputStream("Counter.dat");
DataInputStream din =
new DataInputStream(fin);
i = din.readInt() + 1;
din.close();
} catch (IOException e) {}
Visitor Counter Server (cont'd) Visitor Counter Server (cont'd)
(class CountServer continued.) (class CountServer continued.)

try { OutputStream fout =


ServerSocket s = new ServerSocket(8190); new FileOutputStream("Counter.dat");
while (true) { DataOutputStream dout =
Socket incoming = s.accept(); new DataOutputStream(fout);
DataOutputStream out dout.writeInt(i);
= new DataOutputStream( dout.close();
incoming.getOutputStream()); out.close();
System.out.println("Count: " + i); i++;
out.writeInt(i); }
incoming.close(); } catch (Exception e) {}
System.out.println("CounterServer stopped.");
}

Counter Applet Counter Applet (cont'd)


public class Counter extends Applet {
(class CountServer continued.)
protected int count = 0;
protected Font font = public void paint(Graphics g) {
new Font("Serif", Font.BOLD, 24); int x = 0, y = font.getSize();
g.setColor(Color.green);
public void init() { g.setFont(font);
URL url = getDocumentBase(); g.drawString("You are visitor: " + count,
try { x, y);
Socket t = new Socket(url.getHost(), 8190); }
DataInputStream in = }
new DataInputStream(t.getInputStream());
count = in.readInt();
} catch (Exception e) {}
}
Broadcast Echo Server (cont'd)
Broadcast Echo Server
public class BroadcastEchoServer {
static protected Set activeClients =
new HashSet();
To handle multiple requests simultaneously. public static void main(String[] args) {
Broadcast messages received from any client to int i = 1;
try {
all active clients. ServerSocket s = new ServerSocket(8010);
Need to keep track of all active clients. while (true) {
Socket incoming = s.accept();
BroadcastClientHandler newClient =
new BroadcastClientHandler(incoming, i++);
activeClients.add(newClient);
newClient.start();
}
} catch (Exception e) {}
}
}

Broadcast Client Handler Broadcast Client Handler (cont'd)

public class BroadcastClientHandler


extends Thread { public BroadcastClientHandler(Socket incoming,
int id) {
protected Socket incoming; this.incoming = incoming;
protected int id; this.id = id;
protected BufferedReader in; try {
protected PrintWriter out; if (incoming != null) {
in = new BufferedReader(
public synchronized void new InputStreamReader(
sendMessage(String msg) { incoming.getInputStream()));
if (out != null) {
out.println(msg); out = new PrintWriter(
out.flush(); new OutputStreamWriter(
} incoming.getOutputStream()));
} }
} catch (Exception e) {}
}
Broadcast Client Handler (cont'd) Broadcast Client Handler (cont'd)
// broadcast to other active clients
public void run() { Iterator iter =
if (in != null && BroadcastEchoServer.activeClients.iterator();
out != null) { while (iter.hasNext()) {
sendMessage("Hello! ..."); BroadcastClientHandler t =
sendMessage("Enter BYE to exit."); (BroadcastClientHandler) iter.next();
try { if (t != this)
while (true) { t.sendMessage("Broadcast(" +
String str = in.readLine(); id + "): " + str);
if (str == null) {
break; }}}}
incoming.close();
} else { // this client is no longer active
// echo back to this client BroadcastEchoServer.activeClients.remove(this);
sendMessage("Echo: " + str ); } catch (IOException e) {}
if (str.trim().equals("BYE")) { }
break; }
} else { }

You might also like