TCP CLIENT

//tcpclient.java

import java.io.*;

import java.net.*;

public class tcpclient

{

public static void main(String[] args) throws IOException

{

System.out.println(“TCP CLIENT”);

System.out.println(“Enter the host name to connect”);

DataInputStream inp=new DataInputStream(System.in);

String str=inp.readLine();

Socket clientsoc = new Socket(str, 9);

PrintWriter out = new PrintWriter(clientsoc.getOutputStream(), true);

BufferedReader in = new BufferedReader(new

InputStreamReader(clientsoc.getInputStream()));

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

String userinput;

try

{

while (true)

{

System.out.println(“Sever Says : ” + in.readLine());

userinput = stdin.readLine();

out.println(userinput);

}

}

catch(Exception e)

{

System.exit(0);

}

}

}

TCP SERVER

//tcpserver.java

import java.io.*;

import java.net.*;

public class tcpserver

{

public static void main(String a[]) throws Exception

{

System.out.println(“TCP SERVER”);

System.out.println(“Server is ready to connect…”);

ServerSocket serversoc=new ServerSocket(9);

Socket clientsoc = serversoc.accept();

PrintWriter out = new PrintWriter(clientsoc.getOutputStream(), true);

BufferedReader in = new BufferedReader(new

InputStreamReader(clientsoc.getInputStream()));

String inputline;

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

try

{

while (true)

{

inputline = stdin.readLine();

out.println(inputline);

System.out.println(“Client Says : “+in.readLine());

}

}

catch(Exception e)

{

System.exit(0);

}

}

}

Sample Output:

CLIENT-SERVER CHATTING USING TCP

*************************************

TCP SERVER

************

Server is ready to connect…

hello

Client Says : hello

How are you

Client Says : I’m doing programs

What programs

Client Says : networking

ok.Go ahead

Client Says : ok.Bye

Bye

TCP CLIENT

***********

Enter the host name to connect

p4-221

Sever Says : hello

hello

Sever Says : how are you

I’m doing programs

Sever Says : What programs

networking

Sever Says : ok.Go ahead

ok.Bye

Sever Says : Bye