Aim:Write an echo program with client and concurrent server using TCP.
#Server
import [Link].*;
import [Link].*;
public class Server {
private ServerSocket serverSocket;
Server(int port) {
try
{
serverSocket = new ServerSocket(port);
[Link]("Server waiting for client on port " +
[Link]());
while(true)
{
Socket socket = [Link](); // accept
connection
[Link]("New client asked for a connection");
TcpThread t = new TcpThread(socket); // make a thread of
it
[Link]("Starting a thread for a new Client");
[Link]();
}
}
catch (IOException e) {
[Link]("Exception on new ServerSocket: " + e);
}
}
public static void main(String[] arg) {
new Server(1500);
}
class TcpThread extends Thread {
Socket socket;
ObjectInputStream Sinput;
ObjectOutputStream Soutput;
TcpThread(Socket socket) {
[Link] = socket;
}
public void run() {
[Link]("Thread trying to create Object Input/Output
Streams");
try
{
Soutput = new ObjectOutputStream([Link]());
[Link]();
Sinput = new ObjectInputStream([Link]());
}
catch (IOException e) {
[Link]("Exception creating new Input/output
Streams: " + e);
return;
}
[Link]("Thread waiting for a String from the
Client");
try {
String str = (String) [Link]();
str = [Link]();
[Link](str);
[Link]();
}
catch (IOException e) {
[Link]("Exception reading/writing Streams: " +
e);
return;
}
catch (ClassNotFoundException o) {
}
finally {
try {
[Link]();
[Link]();
}
catch (Exception e) {
}
}
}
}
}
# Client
import [Link].*;
import [Link].*;
public class Client {
ObjectInputStream Sinput;
ObjectOutputStream Soutput;
Socket socket;
Client(int port) {
try {
socket = new Socket("localhost", port);
}
catch(Exception e) {
[Link]("Error connectiong to server:" + e);
return;
}
[Link]("Connection accepted " +
[Link]() + ":" +
[Link]());
try
{
Sinput = new ObjectInputStream([Link]());
Soutput = new ObjectOutputStream([Link]());
}
catch (IOException e) {
[Link]("Exception creating new Input/output Streams:
" + e);
return;
}
String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";
[Link]("Client sending \"" + test + "\" to serveur");
try {
[Link](test);
[Link]();
}
catch(IOException e) {
[Link]("Error writting to the socket: " + e);
return;
}
String response;
try {
response = (String) [Link]();
[Link]("Read back from server: " + response);
}
catch(Exception e) {
[Link]("Problem reading back from server: " + e);
}
try{
[Link]();
[Link]();
}
catch(Exception e) {}
}
public static void main(String[] arg) {
new Client(1500);
}
}